JIAKAOBO

LeetCode

venmo
wechat

感谢赞助!

  • ㊗️
  • 大家
  • offer
  • 多多!

Problem

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: t is "ece" which its length is 3.

Example 2:

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

Code

class Solution {
    public int lengthOfLongestSubstringTwoDistinct(String s) {
        if(s == null || s.length() == 0) return 0;
        HashMap<Character, Integer> map = new HashMap<>();

        int start = 0;
        int index = 0;
        int res = 0;

        while(index < s.length()){
            map.put(s.charAt(index), index);
            index++;

            if(map.size() > 2){
                int leftMost = s.length();
                for(int num : map.values()){
                    leftMost = Math.min(leftMost, num);
                }

                map.remove(s.charAt(leftMost));
                start = leftMost + 1;
            }

            res = Math.max(res, index - start);
        }

        return res;
    }
}