-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathm0003.py
65 lines (52 loc) · 1.49 KB
/
m0003.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
57
58
59
60
61
62
63
64
65
"""Longest Substring Without Repeating Characters
TAG: dynamic-programming, hash-table, string
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.
"""
class DP(object):
"""
Dynamic Programming
"""
@staticmethod
def longest_substr_ending(s: str):
if len(s) == 1:
return s
else:
last = DP.longest_substr_ending(s[:-1])
c = s[-1]
if c in last:
return c
else:
return last + c
@staticmethod
def longest_substr_gen(s: str):
res = s[0]
rem = s[1:]
while True:
yield res
if not rem:
break
c = rem[0]
if c in res:
res = c
else:
res = res + c
rem = rem[1:]
@staticmethod
def longest_substr(s: str):
return max(DP.longest_substr_gen(s), key=lambda x: len(x))
if __name__ == '__main__':
in1 = 'abcabcbb'
in2 = 'bbbbb'
in3 = 'pwwkew'
exp1 = 'abc'
exp2 = 'b'
exp3 = 'wke'
assert DP.longest_substr(in1) == exp1
assert DP.longest_substr(in2) == exp2
assert DP.longest_substr(in3) == exp3