2014年12月1日星期一

[Leetcode] Longest Substring Without Repeating Characters

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.

Use a window to keep the longest substring without repeating characters. Whenever we find a repeating character, move the left side of the window until we meet this character.


    public int lengthOfLongestSubstring(String s) {
        int n = s.length();
        if(n == 0)
            return 0; // corner case
        int p1 = 0, p2 = 0, res = Integer.MIN_VALUE;
        HashSet<Character> set = new HashSet<Character>();
        while(p1 < n) {
            while(p2 < n && set.contains(s.charAt(p2)) == false) {
                set.add(s.charAt(p2));
                p2++;
            }
            res = Math.max(res, p2 - p1);
            if(p2 == n) { // all cases have been examined
                break;
            }
            char ch = s.charAt(p2);
            while(p1 < n && s.charAt(p1) != ch) { // move all characters that is before the duplicate out
                set.remove(s.charAt(p1));
                p1++;
            }
            p1++; p2++; // remember to move p2 forward
        }
        return res;
    }

没有评论:

发表评论