3.Longest Substring without repeating characters

public class Solution {
    public int lengthOfLongestSubstring(String s) {
        if (s == null || s.length() == 0) {
            return 0;
        }
        
        HashSet<Character> hs = new HashSet<Character>();
        int leftbound = 0;
        int max = 0;
        for (int i = 0; i < s.length(); i++) {
            if (hs.contains(s.charAt(i))) {
                while (leftbound < i && s.charAt(leftbound) != s.charAt(i)) {
                    hs.remove(s.charAt(leftbound));
                    leftbound++;
                }
                leftbound++;
            } else {
                hs.add(s.charAt(i));
                max = Math.max(max, i - leftbound + 1);
            }
            
        }
        return max;
    }
}

 

posted on 2015-06-02 05:21  kikiUr  阅读(99)  评论(0编辑  收藏  举报