Share my O(n) Java solution, two pointers


  • 0

    Easy one, have two pointers left and right. Count up/down based on boundary condition.

    public class Solution {
        public int lengthOfLongestSubstringTwoDistinct(String s) {
            if (s == null || s.length() == 0) return 0;
            int[] map = new int[256];
            int l = 0, r = 0, k = 0, maxLen = 0;
            
            while (r < s.length()) {
                if (k <= 2) {
                    char c = s.charAt(r++);
                    if (map[c] == 0) k++;
                    map[c]++;
                    if (k <= 2) maxLen = Math.max(maxLen, r - l);
                } else {
                    char c = s.charAt(l++);
                    if (map[c] == 1) k--;
                    map[c]--;
                }
            }
            return maxLen;
        }
    }
    

Log in to reply
 

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