Tuesday, August 18, 2015

Leetcode - Longest Substring Without Repeating Characters

Problem

Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.

Accepted Solution

public class Solution {
     public int lengthOfLongestSubstring(String s) {

  int len=0; int start=0, pos=0, curLen=0, i=0;
  HashMap map = new HashMap();
  for(; i< s.length(); i++) 
                {
   if(map.containsKey(s.charAt(i)))
   {
    pos = map.get(s.charAt(i));
    curLen = i-start;
    if(curLen > len) len = curLen;
    if(pos >= start) start=pos+1;
   } 
   map.put(s.charAt(i),i);   
  }
  if(i== s.length() && i> 0) 
                {
          curLen = i-start;
   if(curLen > len) len = curLen;
  }
  return len;
 }
}

No comments:

Post a Comment