Java Easy to understand sliding window using HashMap


  • 0
    D
    public class Solution {
        public int lengthOfLongestSubstringTwoDistinct(String s) 
        {
            if (s == null || s.isEmpty()) { return 0; }
            
            // sliding window boundary pointers
            int left = 0;
            int right = 0;
            
            // map stores character and its occurrence
            Map<Character, Integer> map = new HashMap<>();
            int maxLen = 0;
            while (right < s.length())
            {
                if (map.size() <= 2)
                {
                    char c = s.charAt(right);
                    map.put(c, map.getOrDefault(c, 0) + 1);
                    right++;
                }
                else
                {
                    // move left pointer
                    maxLen = Math.max(maxLen, right - left - 1);
                    char c = s.charAt(left);
                    
                    int leftCharFreq = map.get(c);
                    // remove char from map if its occurrence = 0
                    if (leftCharFreq - 1 == 0)
                    {
                        map.remove(c);
                    }
                    else
                    {
                        map.put(c, leftCharFreq - 1);
                    }
                    left++;
                }
    
            }
            // final check
            if (map.size() > 2)
            {
                maxLen = Math.max(maxLen, right - left - 1);
            }
            else
            {
                maxLen = Math.max(maxLen, right - left);
            }
    
            return maxLen;
        }
    }
    

Log in to reply
 

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