Saturday, January 10, 2015

Longest Substring Without Repeating Characters (LeetCode String)

Question: 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.

Idea: Two pointers.  Use two pointers leftBound and i to maintain a slide window. Use a hashset<characters appeared> to cache the characters in the window. The pointer i traverses from left to right. If string[i] is a character appeared in the hashset, push leftBound forward and pop the corresponding character until string[i] can be added into the window (the same character appeared before was popped). If string[i] is a character not in the hashset, push i forward to check the next character.

Time: O(n) Space: O(1)

Code:
 public class Solution {  
   public int lengthOfLongestSubstring(String s) {  
     if(s.length()<=1)  
       return s.length();  
     HashSet<Character> found=new HashSet<Character>();  
     int leftBound=0;  
     int result=0;  
     for(int i=0;i<s.length();i++)  
     {  
       char c=s.charAt(i);  
       while(found.contains(c)&&leftBound<s.length())  
       {  
         char cur=s.charAt(leftBound);  
         found.remove(cur);  
         leftBound++;  
       }  
       found.add(c);  
       result=Math.max(result,found.size());  
     }  
     return result;  
   }  
 }  

No comments:

Post a Comment