My solution in java, three pointers, O(n) time

  • 0

    I'd like to share my solution. There is no need to use hashmap to store the count of each char in the substring in this question. My solution uses another pointer to store the last position that we change char in substring. But my solution only works in k=2 situation. I like the hashmap solution better because it can extend to k situation.

    public int lengthOfLongestSubstringTwoDistinct(String s) {
        char[] chars = s.toCharArray();
        if(chars.length == 0){
            return 0;
        int start = 0;
        int change = 0;
        Set<Character> temp = new HashSet<Character>();
        int max = 0;
        int end = 1;
        while(end < chars.length){
            if(chars[end] != chars[end - 1]){
                if(temp.size() > 2){
                    max = Math.max(max, end - start);
                    start = change;
                change = end;
        return Math.max(max, end - start);

Log in to reply

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