Longest Substring Without Repeating Characters [Solution]
Here’s a Python implementation of the length_of_longest_substring
function to find the length of the longest substring without
repeating characters:
def length_of_longest_substring(s: str) -> int:
"""
Find the length of the longest substring without repeating characters.
Parameters:
- s: Input string.
Returns:
- int: Length of the longest substring without repeating characters.
"""
char_index_map = {} # Map to store the index of each character in the substring
start_index = 0 # Starting index of the current substring
max_length = 0 # Length of the longest substring without repeating characters
for i, char in enumerate(s):
if char in char_index_map and char_index_map[char] >= start_index:
# If the character is repeated and its index is within the current substring
start_index = char_index_map[char] + 1
# Update the index of the character in the substring
char_index_map[char] = i
# Update the length of the longest substring
max_length = max(max_length, i - start_index + 1)
return max_length
# Example usage:
s1 = "abcabcbb"
result1 = length_of_longest_substring(s1)
print(result1) # Output: 3
s2 = "bbbbb"
result2 = length_of_longest_substring(s2)
print(result2) # Output: 1
s3 = "pwwkew"
result3 = length_of_longest_substring(s3)
print(result3) # Output: 3
s4 = "abcde"
result4 = length_of_longest_substring(s4)
print(result4) # Output: 5
This solution uses a sliding window approach to efficiently find the length of the longest substring without repeating characters.
Time Complexity:
The time complexity is O(n)
,
where n
is the length of the input string.
Space Complexity:
The space complexity is O(min(m, n))
,
where m
is the size of the character set
(in this case, lowercase English letters).