zoukankan      html  css  js  c++  java
  • [LC] 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.

    Time: O(N)
    Space: O(N)
     1 class Solution:
     2     def lengthOfLongestSubstringTwoDistinct(self, s: str) -> int:
     3         res = 0
     4         start, end, count = 0, 0, 0
     5         my_dict = {}
     6         while end < len(s):
     7             end_char = s[end]
     8             end_freq = my_dict.get(end_char, 0)
     9             my_dict[end_char] = end_freq + 1
    10             if end_freq == 0:
    11                 count += 1
    12             end += 1
    13             // cannot use count <= 2 to get res b/c end will run before start
    14             while count > 2:
    15                 start_char = s[start]
    16                 start_freq = my_dict[start_char]
    17                 my_dict[start_char] = start_freq - 1
    18                 if start_freq == 1:
    19                     count -= 1
    20                 start += 1
    21             res = max(res, end - start)
    22         return res
  • 相关阅读:
    [CF528D] Fuzzy Search
    [WC2013] 糖果公园
    [APIO2011] 方格染色
    [CTSC2017] 吉夫特
    [HNOI/AHOI2018] 转盘
    [CTSC2008] 网络管理
    [HAOI2018] 苹果树
    [SCOI2016] 萌萌哒
    git创建分支并提交项目
    git 常规操作
  • 原文地址:https://www.cnblogs.com/xuanlu/p/11675476.html
Copyright © 2011-2022 走看看