My concise solution in Java


  • 1
    Z

    A map to store the right most index of two distinct characters. 1 pointer to store the start index of the substring. The pointer only changes under one condition: the current substring already has two unique characters and the current character is the third character.

    public int lengthOfLongestSubstringTwoDistinct(String s) {
        HashMap<Character, Integer> hm = new HashMap<>();
        int longest = 0;
        int ptr = 0;
        for(int i = 0; i < s.length(); i++) {
            if(!hm.containsKey(s.charAt(i)) && hm.size() == 2) {
                int leftmost = Collections.min(hm.values());
                hm.remove(s.charAt(leftmost));
                ptr = s.indexOf((char) hm.keySet().toArray()[0], leftmost);
            }
            hm.put(s.charAt(i), i);
            longest = Math.max(longest, i - ptr + 1);
        }
        return longest;
    }

Log in to reply
 

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