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;
    }
}

 

Given a string s , find the length of the longest substring t  that contains at most 2 distinct characters.

Example 1:

Input: "eceba"
Output: 3
Explanation: tis "ece" which its length is 3.

Example 2:

Input: "ccaabbb"
Output: 5
Explanation: tis "aabbb" which its length is 5.

posted on 2018-08-11 04:55  猪猪&#128055;  阅读(119)  评论(0)    收藏  举报

导航