Longest Substring with At Most Two Distinct Characters

Given a string, find the length of the longest substring T that contains at most 2 distinct characters.

For example, Given s = “eceba”,


public class Solution {
    public int lengthOfLongestSubstringTwoDistinct(String s) {

        if ( s == null || s.length() == 0 ) return 0;
        HashMap<Character, Integer> set = new HashMap<Character, Integer>();

        int i = 0 ; 
        int j = 0;
        int res = 0;
        for (i = 0; i < s.length(); i++) {
            while( j < s.length() ){
                if(set.containsKey(s.charAt(j))){
                    set.put(s.charAt(j), set.get(s.charAt(j)) + 1);
                    j++;
                    continue;
                }else{
                    if(set.size() == 2)
                        break;
                    set.put(s.charAt(j), 1);
                    j++;
                    continue;
                }
            }

            res = Math.max(res, j - i);
            int cur = set.get(s.charAt(i));
            if (cur - 1 == 0){
                set.remove(s.charAt(i));
            }else{
                set.put(s.charAt(i), cur - 1);
            }

        }
        return res;
    }
}

results matching ""

    No results matching ""