Tuesday, October 8, 2013

Longest Substring Without Repeating Characters

Q:
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.
A:

--------------第二遍------用HashSet, 增加了效率-------------

public class Solution { 
    public int lengthOfLongestSubstring(String s) {
        int maxLen = 0, start = 0;
        Set<Character> set = new HashSet();
        for(int end =0;end<s.length();end++){
            char newChar = s.charAt(end);
            while(set.contains(newChar))
                set.remove(s.charAt(start++));
            set.add(newChar);
            maxLen = Math.max(maxLen, end - start + 1);
        }
        return maxLen;
    }
} 

-----------

Mistakes:
1: when we find the current char,  we need update the maxLenEndHere,    so, when minus the length that we removed ,we also need add 1 because of the current char that we just encountered.

2: 别忘了加上刚刚遇到的char

Learned:

------------------------------1rd  pass-----------------
public class Solution {
    public int lengthOfLongestSubstring(String s) {
        if(s==null || s.length() ==0)
            return 0;
        // use HashMap,  
        HashSet<Character> set = new HashSet<Character>();
        int maxLength = 0;
        for(int i =0;i<s.length();i++){
            char ch = s.charAt(i);
            if(! set.contains(ch)){
                set.add(ch);
                maxLength = Math.max(maxLength, set.size());
            }else{ // delete until no match
                int j = i - set.size();
                while(set.contains(ch)){
                    char newCh = s.charAt(j);
                    set.remove(newCh);
                    j++;
                }
                set.add(ch);
            }
        }
        return maxLength;
    }
}





No comments:

Post a Comment