Java sliding window with two pointers


  • 0
    Y

    I used a hashmap to keep the character counts. The two pointers will give a dynamic sized sliding window. It can be easily extended for k characters.

        public int lengthOfLongestSubstringTwoDistinct(String s) {
            Map<Character, Integer> map = new HashMap<>();
            int j = 0, n = s.length(), best = 0;
            for(int i = 0; i < n; i++) {
                while(j < n && map.size() <= 2) {
                    map.put(s.charAt(j), map.getOrDefault(s.charAt(j), 0) + 1);
                    if(map.size() <= 2) {
                        best = Math.max(best, j-i+1);
                    }
                    j++;
                }
                int count = map.get(s.charAt(i));
                if(count == 1) {
                    map.remove(s.charAt(i));
                } else {
                    map.put(s.charAt(i), count - 1);
                }
            }
            return best;
        }

Log in to reply
 

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