-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlengthOfLongestSubstring.py
More file actions
28 lines (22 loc) · 921 Bytes
/
lengthOfLongestSubstring.py
File metadata and controls
28 lines (22 loc) · 921 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
#https://leetcode.com/problems/longest-substring-without-repeating-characters/
#Given a string s, find the length of the longest substring without repeating characters.
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
max_so_far = 0
hm = {}
start = 0
for i in range(len(s)):
if(s[i] in hm):
start = max(hm[s[i]] + 1, start)
max_so_far = max(max_so_far, i-start+1)
hm[s[i]] = i
return max_so_far
'''
Algorithm:
-> Iterate through the string, if the current character is already present in dictionary, update the start of the required substring
-> If current character does not exist in dictionary, add the character-index as key-value pairs into it, else update the value of character.
-> Update the length of the maximum length substring
Complexities:
Space - O(n)
Time - O(n)
'''