Given a string s
, return the length of the longest
substring that contains at most two distinct characters.
Example 1:
Input: s = "eceba" Output: 3 Explanation: The substring is "ece" which its length is 3.
Example 2:
Input: s = "ccaabbb" Output: 5 Explanation: The substring is "aabbb" which its length is 5.
Constraints:
1 <= s.length <= 105
s
consists of English letters.
I pass the problem in my first try, but my solution is not smart enough. I remember the first character and the second character last position then do some math. Therefore, I can know the length difference. Only need to memorize the longest one.
class Solution:
def lengthOfLongestSubstringTwoDistinct(self, s: str) -> int:
if len(s) == 1:
return 1
table = {}
longest = 0
c_length = 0
for i in range(0, len(s)):
keys = list(table.keys())
if s[i] in keys or len(keys) < 2:
table[s[i]] = i
c_length += 1
else:
longest = c_length if c_length > longest else longest
f_i = table[keys[0]]
s_i = table[keys[1]]
if f_i > s_i:
del table[keys[1]]
else:
del table[keys[0]]
c_length = abs(f_i - s_i) + 1
table[s[i]] = i
return c_length if c_length > longest else longest
However, I saw there is a brilliant solution. Much cleaner and simpler, but need some time to think about it.
class Solution:
def lengthOfLongestSubstringTwoDistinct(self, s: str) -> int:
count, i = {}, 0
for j, k in enumerate(s):
count[k] = count.get(k, 0) + 1
if len(count) > 2:
count[s[i]] -= 1
if count[s[i]] == 0:
del count[s[i]]
i += 1
return j - i + 1
搶先發佈留言