-
Notifications
You must be signed in to change notification settings - Fork 19
/
answer.py
48 lines (41 loc) · 1.25 KB
/
answer.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
#!/usr/bin/python
class Solution(object):
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
length = 0
i = 0
j = 0
substring = set()
while i < len(s) and j < len(s):
if not s[i] in substring:
substring.add(s[i])
i += 1
length = max(length, i - j)
else:
substring.remove(s[j])
j += 1
return length
#-------------------------------------------------------------------------------
# Optimized o(n) solution
class Optimized(object):
def lengthOfLongestSubstring(self, s):
length = 0
i = 0
j = 0
dict = {}
for j in range (0, len(s)):
if s[j] in dict:
i = max(dict[s[j]], i)
length = max(length, j - i + 1)
dict[s[j]] = j + 1
return length
#-------------------------------------------------------------------------------
#Testing
def main():
x = Optimized()
y = x.lengthOfLongestSubstring("abcdedfffqwertyuioplkjtksladnf")
print y
main()