forked from keon/algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
longest_non_repeat.py
46 lines (42 loc) · 1.2 KB
/
longest_non_repeat.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
"""
Given a string, find the length of the longest substring
without repeating characters.
Examples:
Given "abcabcbb", the answer is "abc", which the length is 3.
Given "bbbbb", the answer is "b", with the length of 1.
Given "pwwkew", the answer is "wke", with the length of 3.
Note that the answer must be a substring,
"pwke" is a subsequence and not a substring.
"""
def longest_non_repeat_v1(string):
"""
Finds the length of the longest substring
without repeating characters.
"""
if string is None:
return 0
temp = []
max_len = 0
for i in string:
if i in temp:
temp = []
temp.append(i)
max_len = max(max_len, len(temp))
return max_len
def longest_non_repeat_v2(string):
"""
Finds the length of the longest substring
without repeating characters.
Uses alternative algorithm.
"""
if string is None:
return 0
start, max_len = 0, 0
used_char = {}
for index, char in enumerate(string):
if char in used_char and start <= used_char[char]:
start = used_char[char] + 1
else:
max_len = max(max_len, index - start + 1)
used_char[char] = index
return max_len