forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmaximum-length-substring-with-two-occurrences.py
46 lines (43 loc) · 1.2 KB
/
maximum-length-substring-with-two-occurrences.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# Time: O(n + 26)
# Space: O(26)
# freq table, sliding window, two pointers
class Solution(object):
def maximumLengthSubstring(self, s):
"""
:type s: str
:rtype: int
"""
COUNT = 2
result = 0
cnt = [0]*26
left = invalid_cnt = 0
for right, x in enumerate(s):
if cnt[ord(x)-ord('a')] == COUNT:
invalid_cnt += 1
cnt[ord(x)-ord('a')] += 1
if invalid_cnt:
cnt[ord(s[left])-ord('a')] -= 1
if cnt[ord(s[left])-ord('a')] == COUNT:
invalid_cnt -= 1
left += 1
return right-left+1
# Time: O(n + 26)
# Space: O(26)
# freq table, sliding window, two pointers
class Solution2(object):
def maximumLengthSubstring(self, s):
"""
:type s: str
:rtype: int
"""
COUNT = 2
result = 0
cnt = [0]*26
left = 0
for right, x in enumerate(s):
cnt[ord(x)-ord('a')] += 1
while cnt[ord(x)-ord('a')] > COUNT:
cnt[ord(s[left])-ord('a')] -= 1
left += 1
result = max(result, right-left+1)
return result