Skip to content

Commit 32ee3ff

Browse files
authored
Update longest-substring-with-at-most-two-distinct-characters.py
1 parent 51b6395 commit 32ee3ff

File tree

1 file changed

+23
-2
lines changed

1 file changed

+23
-2
lines changed

Python/longest-substring-with-at-most-two-distinct-characters.py

+23-2
Original file line numberDiff line numberDiff line change
@@ -10,13 +10,34 @@ def lengthOfLongestSubstringTwoDistinct(self, s):
1010
if visited[ord(char)] == 0:
1111
distinct_count += 1
1212
visited[ord(char)] += 1
13-
1413
while distinct_count > 2:
1514
visited[ord(s[start])] -= 1
1615
if visited[ord(s[start])] == 0:
1716
distinct_count -= 1
1817
start += 1
19-
2018
longest = max(longest, i - start + 1)
2119
return longest
2220

21+
22+
# Time: O(n)
23+
# Space: O(1)
24+
from collections import Counter
25+
26+
27+
class Solution2(object):
28+
def lengthOfLongestSubstringTwoDistinct(self, s):
29+
"""
30+
:type s: str
31+
:rtype: int
32+
"""
33+
counter = Counter()
34+
left, max_length = 0, 0
35+
for right, char in enumerate(s):
36+
counter[char] += 1
37+
while len(counter) > 2:
38+
counter[s[left]] -= 1
39+
if counter[s[left]] == 0:
40+
del counter[s[left]]
41+
left += 1
42+
max_length = max(max_length, right-left+1)
43+
return max_length

0 commit comments

Comments
 (0)