Skip to content

Commit 36239c4

Browse files
committed
Add 159
1 parent e4f4a3e commit 36239c4

File tree

3 files changed

+38
-0
lines changed

3 files changed

+38
-0
lines changed

Readme.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@
3838
| 152 | Maximum Product Subarray | Medium | O(N) | O(N) | Dynamic Programming, Array | | |
3939
| 153 | Find Minimum in Rotated Sorted Array | Medium | O(logN) | O(1) | Binary Search | | |
4040
| 154 | Find Minimum in Rotated Sorted Array II | Hard | O(logN) | O(1) | Binary Search | | |
41+
| 159 | Longest Substring with At Most Two Distinct Characters | Medium | O(N) | O(1) | Premium, Hash Table, Two Pointers, String, Sliding Window | | |
4142
| 165 | Compare Version Numbers | Medium | O(N) | O(1) | String | | |
4243
| 171 | Excel Sheet Column Number | Easy | O(N) | O(1) | String | | |
4344
| 179 | Largest Number | Medium | O(NlogN) | O(1) | Sort | | |

src/159.py

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
# TAGS: Premium, Hash Table, Two Pointers, String, Sliding Window
2+
3+
class Solution:
4+
# 360 ms, 5.36%. Time: O(N). Space; O(1)
5+
def lengthOfLongestSubstringTwoDistinct(self, s: str) -> int:
6+
def valid(counter):
7+
return len(list(v for v, f in counter.items() if f > 0)) <= 2
8+
9+
counter = collections.Counter()
10+
left = ans = 0
11+
for right, c in enumerate(s):
12+
counter[c] += 1
13+
if not valid(counter):
14+
while not valid(counter):
15+
counter[s[left]] -= 1
16+
left += 1
17+
ans = max(ans, right - left + 1)
18+
return ans
19+
20+
# 40 ms, 98.59%. Time: O(N). Space; O(1)
21+
def lengthOfLongestSubstringTwoDistinct1(self, s: str) -> int:
22+
counter = {}
23+
left = ans = 0
24+
for right, c in enumerate(s):
25+
counter[c] = right
26+
if len(counter) > 2:
27+
left = min(counter.values())
28+
del counter[s[left]]
29+
left += 1
30+
ans = max(ans, right - left + 1)
31+
return ans

testcases/159

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
"eceba"
2+
"ccaabbb"
3+
"a"
4+
""
5+
"aabaac"
6+
"baabaacaa"

0 commit comments

Comments
 (0)