a very simple java solution use hash map


  • 0
    S
    public int lengthOfLongestSubstringTwoDistinct(String s) {
        int i = 0, j = -1, length = 0, count = 0;
        HashMap<Character, Integer> visited = new HashMap<Character, Integer>();
        while (++j < s.length()) {
            char c = s.charAt(j);
            if (!visited.containsKey(c) || visited.get(c) < i) count++;
            visited.put(c, j);
            if (count > 2) {
                length = Math.max(length, j - i);
                while (visited.get(s.charAt(i)) != i++);
                count--;
            }
        }
        return Math.max(length, j - i);
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.