-
Notifications
You must be signed in to change notification settings - Fork 9
/
3.Longest_Substring_Without_Repeating_Characters.py
45 lines (37 loc) · 1.29 KB
/
3.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
class Solution(object):
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
if len(s) == 0: return 0
if len(s) == 1: return 1
repeat_word_dict = {}
max_cnt = 0
cur_left = 0
cur_pos = 0
cur_cnt = 0
while cur_left < len(s):
if s[cur_pos] not in repeat_word_dict.keys():
repeat_word_dict[s[cur_pos]] = cur_pos
else:
if repeat_word_dict[s[cur_pos]] < cur_left:
repeat_word_dict[s[cur_pos]] = cur_pos
else:
cur_cnt = cur_pos - cur_left
if cur_cnt > max_cnt: max_cnt = cur_cnt
cur_left = repeat_word_dict[s[cur_pos]] + 1
cur_cnt = cur_pos - cur_left + 1
repeat_word_dict[s[cur_pos]] = cur_pos
cur_pos += 1
if cur_pos == len(s):
cur_cnt = cur_pos - cur_left
if cur_cnt > max_cnt: max_cnt = cur_cnt
return max_cnt
if cur_left == len(s):
if cur_cnt > max_cnt: max_cnt = cur_cnt
return max_cnt
if __name__ == '__main__':
s = Solution()
result = s.lengthOfLongestSubstring("pwwkew")
print(result)