标签:end cannot char for length ann def nbsp dict
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
标签:end cannot char for length ann def nbsp dict
原文地址:https://www.cnblogs.com/xuanlu/p/11675476.html