O(n) time O(1) space Java solution


  • 0
    J
        public int lengthOfLongestSubstringTwoDistinct(String s) {
            int[] cnts = new int[256];
            int start = 0, end = 0, maxLen = 0, counter = 0, startSave = 0;
            while (end < s.length()) {
                char c = s.charAt(end);
                if (cnts[c] == 0) counter++;
                cnts[c]++;
                end++;
                while (counter > 2) {
                    char cs = s.charAt(start);
                    cnts[cs]--;
                    if (cnts[cs] == 0) counter--;
                    start++;
                }
                if (end - start > maxLen) {
                    maxLen = end - start;
                    startSave = start;
                }
            }
            return maxLen;
        }
    

Log in to reply
 

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