[LC] 159. Longest Substring with At Most Two Distinct Characters
Posted xuanlu
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[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
以上是关于[LC] 159. Longest Substring with At Most Two Distinct Characters的主要内容,如果未能解决你的问题,请参考以下文章
159 Longest Substring with At Most Two Distinct Characters
[LeetCode] 159. Longest Substring with At Most Two Distinct Characters
算法159题 Longest Substring with at Most Two Distinct Characters 最大的子串
[LC] 14. Longest Common Prefix