-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path09function.py
More file actions
27 lines (18 loc) · 891 Bytes
/
09function.py
File metadata and controls
27 lines (18 loc) · 891 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
"""
Returns the length of the longest substring
without repeating characters.
"""
def length_of_longest_substring(s: str) -> int:
char_index = {} # Stores last seen index of each character
left = 0 # Left pointer of sliding window
max_length = 0 # Maximum length found
for right in range(len(s)):
if s[right] in char_index and char_index[s[right]] >= left: # If character seen before and inside current window
left = char_index[s[right]] + 1
char_index[s[right]] = right # Update last seen index
window_length = right - left + 1 # Calculate current window size
max_length = max(max_length, window_length)
return max_length
user_input = input("Enter a string: ")
result = length_of_longest_substring(user_input)
print("Length of longest substring:", result)