zoukankan      html  css  js  c++  java
  • 159. Longest Substring with At Most Two Distinct Characters

    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.

    3. Longest Substring Without Repeating Characters - Medium 类似,用counter计数,如果map中对应value == 1,说明这是一个新的字符,counter++。当counter > 2时进入while循环开始移动slow。更新map中slow对应字符的value(-1),如果更新完value为0,counter--。

    time: O(n), space: O(n)

    class Solution {
        public int lengthOfLongestSubstringTwoDistinct(String s) {
            Map<Character, Integer> map = new HashMap<>();
    
            int slow = 0, fast = 0, counter = 0, d = 0;
            while(fast < s.length()) {
                char c = s.charAt(fast);
                map.put(c, map.getOrDefault(c, 0) + 1);
                if(map.get(c) == 1)
                    counter++;
                fast++;
                
                while (counter > 2) {
                    char tmp = s.charAt(slow);
                    map.put(tmp, map.get(tmp) - 1);
                    if (map.get(tmp) == 0)
                        counter--;
                    slow++;
                }
                d = Math.max(d, fast - slow);
            }
            return d;
        }
    }

    另一种写法:

    class Solution {
        public int lengthOfLongestSubstringTwoDistinct(String s) {
            if(s == null || s.length() == 0) {
                return 0;
            }
            Map<Character, Integer> map = new HashMap<>();
            int slow = 0, fast = 0, counter = 0, len = 0;
            while(fast < s.length()) {
                char f = s.charAt(fast);
                map.put(f, map.getOrDefault(f, 0) + 1);
                fast++;
                
                while(map.size() > 2) {
                    char c = s.charAt(slow);
                    map.put(c, map.get(c) - 1);
                    if(map.get(c) == 0) {
                        map.remove(c);
                    }
                    slow++;
                }
                len = Math.max(len, fast - slow);
            }
            return len;
        }
    }
  • 相关阅读:
    python实现从生成器中取固定角标的元素
    python-高阶函数
    git学习手册
    python批量进行文件修改操作
    python第一站
    LoadRunner,一个简单的例子
    python3中urllib2的问题
    gitlab 随笔
    sed 删除文本
    sed 修改文本
  • 原文地址:https://www.cnblogs.com/fatttcat/p/10302350.html
Copyright © 2011-2022 走看看