• 159. Longest Substring with At Most Two Distinct Characters 159.最长两个不同字符的子字符串


    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.


    不是counter > 2就要返回,而是counter > 2就要控制

    只有出现了一次的新字母需要控制,所以只有
    if(map.get(c) == 1) counter++;
    if(map.get(cTemp) == 0)时counter--; 
    public class Solution {
        public int lengthOfLongestSubstringTwoDistinct(String s) {
            Map<Character, Integer> map = new HashMap<>();
            int begin = 0, end = 0, counter = 0, d = 0;
    
            while (end < s.length()) {
                char c = s.charAt(end);
                map.put(c, map.getOrDefault(c, 0) + 1);
                if(map.get(c) == 1) counter++;
                end++;
                
                while (counter > 2) {
                    char charTemp = s.charAt(begin);
                    map.put(charTemp, map.get(charTemp)-1);
                    if (map.get(charTemp) == 0) counter--;                
                    begin++;
    
                }
                if (end - begin > d) 
                    d = end - begin;
            }
            return d;
        }
    }
    View Code
  • 相关阅读:
    postcss-pxtorem
    git命令记录
    伪类和伪元素
    JavaScript设计模式
    每日思考(2020/09/08)
    每日思考(2020/09/03)
    每日思考(2020/09/02)
    每日思考(2020/09/01)
    每日思考(2020/08/31)
    每日思考(2020/08/27)
  • 原文地址:https://www.cnblogs.com/immiao0319/p/13412808.html
Copyright © 2020-2023  润新知