首页 > 代码库 > 159. Longest Substring with At Most Two Distinct Characters

159. Longest Substring with At Most Two Distinct Characters

技术分享

 public int lengthOfLongestSubstringTwoDistinct(String s) {      //sliding window        if(s == null || s.length() < 3)            return s.length();        Set<Character> set = new HashSet<>();        int max = 0, index = 0;                                 // use index to record left bar of window        for(int i = 0; i < s.length(); i++) {            char c = s.charAt(i);            if(!set.contains(c)) {                if(set.size() >= 2) {                    for(int j = i - 1; j >= 0; j--)             // scan from i - 1 to 0                        if(s.charAt(j) != s.charAt(i - 1)) {                            set.remove(s.charAt(j));                            index = j + 1;                            break;                        }                }                 set.add(c);            }            max = Math.max(i - index + 1, max);        }        return max;    }

 

159. Longest Substring with At Most Two Distinct Characters