zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    Ellipsis 的升级版 line-clamp
    Angular7里面实现 debounce search
    闭包、迭代器
    Day10 函数的进阶
    函数
    文件的操作
    Day 07基础数据补充、set、深浅拷贝
    小数据池,编码和解码
    字典
    列表、元祖的操作
  • 原文地址:https://www.cnblogs.com/immiao0319/p/13412808.html
Copyright © 2011-2022 走看看