-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathlongest-substring-without-repeating-characters.py
56 lines (38 loc) · 1.24 KB
/
longest-substring-without-repeating-characters.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
47
48
49
50
51
52
53
54
55
56
from typing import Counter
class Solution:
def lengthOfLongestSubstring(self, s):
left, right = 0, 0
counter: Counter[str] = Counter()
repeating = 0
longest_substring = 0
while right < len(s):
while left + 1 < right and repeating > 0:
counter[s[left]] -= 1
if counter[s[left]] == 1:
repeating -= 1
left += 1
while repeating == 0:
longest_substring = max(longest_substring, right - left)
if right == len(s):
break
counter[s[right]] += 1
if counter[s[right]] == 2:
repeating += 1
right += 1
return longest_substring
def lengthOfLongestSubstring1(self, s):
"""
:type s: str
:rtype: int
"""
str_hash_map = {}
longest_substr = 0
left = 0
right = 0
for n, c in enumerate(s):
if c in str_hash_map:
left = max(str_hash_map[c] + 1, left)
str_hash_map[c] = n
right = n
longest_substr = max(longest_substr, right - left + 1)
return longest_substr