-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLengthOfLongestSubString.py
More file actions
33 lines (31 loc) · 943 Bytes
/
LengthOfLongestSubString.py
File metadata and controls
33 lines (31 loc) · 943 Bytes
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
"""
https://leetcode.com/problems/longest-substring-without-repeating-characters/description/#
#hash-table #string #slicing-window #two-pointer
"""
class Solution:
def lengthOfLongestSubstring(self, s):
"""
O(n)
"""
hashMap = {}
maxLength = 0
subLength = 0
firstIndex = 0
for i in range(len(s)):
if s[i] in hashMap:
if hashMap.get(s[i]) < firstIndex :
subLength += 1
else:
maxLength = max(maxLength, subLength)
firstIndex = hashMap.get(s[i]) + 1
subLength = i - firstIndex + 1
else:
subLength += 1
hashMap.update({s[i] : i})
return max(subLength, maxLength)
#test
def main():
str = "dvdfgfd"
print(Solution().lengthOfLongestSubstring(str))
if __name__ == '__main__':
main()