159. Longest Substring with At Most Two Distinct Characters

class Solution {
    public int lengthOfLongestSubstringTwoDistinct(String s) {
      int k = 2;
      if(s == null || s.length() == 0){
          return 0;
      }
      if(s.length() <= k){
          return s.length();
      }
      int slow = 0;
      HashMap<Character, Integer> map = new HashMap<>();
      int maxLen = k;
      
      for(int fast = 0; fast < s.length(); fast++){
        char current = s.charAt(fast);
        Integer curCount = map.get(current);
        if(curCount == null){
          map.put(current, 1);
        }else{
          map.put(current, curCount + 1);
        }
        
        
        
        while(map.size() > k){
          // when the number of distince chars in the current window is bigger than k
          // we need to move the slow pointer
          char c = s.charAt(slow++);
          Integer count = map.get(c);
          if(count == 1){
            map.remove(c);
          }else{
            map.put(c, count - 1);
          }
        }
        
        maxLen = Math.max(maxLen, fast - slow + 1);
      }
      return maxLen;
    }
}

猜你喜欢

转载自www.cnblogs.com/tobeabetterpig/p/9458393.html
今日推荐