Easy to understand O(n) JAVA solution, easy extend to k characters.


  • 0
    F

    Just change chars > 2 to chars > k.

            int max = 0;
            int chars = 0; //How many different chars so far.
            for (int i = 0, j = 0; i < s.length(); i++) {
                if (map[s.charAt(i)]++ == 0) {
                    chars++;
                }
                while (chars > 2) {
                    if (map[s.charAt(j++)]-- == 1) {
                        chars--;
                    }
                }
                max = Math.max(max, i - j + 1);
            }
            return max;

Log in to reply
 

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