The task is to find the length of the longest substring in a given string that does not contain any repeating characters. For instance, in the string “abcabcbb”, the longest substring without repeating characters is “abc”, which has a length of 3.
def length_of_longest_substring(s: str) -> int:
char_map, left, max_length = {}, 0, 0
for right, char in enumerate(s):
if char in char_map and char_map[char] >= left:
left = char_map[char] + 1
char_map[char] = right
max_length = max(max_length, right - left + 1)
return max_length
# Example usage
print(length_of_longest_substring("abcabcbb")) # Output: 3
The provided code defines a function length_of_longest_substring
that takes a string s
as input and returns the length of the longest substring without repeating characters.
- Sliding Window Approach: The algorithm uses a sliding window technique, where
left
andright
pointers define the current substring being considered.right
pointer iterates over the string, whileleft
is adjusted to ensure that there are no repeated characters in the current substring. - Using a Dictionary:
char_map
keeps track of the most recent index of each character in the string. If a character repeats (i.e., it’s already inchar_map
and its index is greater than or equal toleft
), it means the window has a repeat character, and we adjustleft
to skip past the previous occurrence of the character. - Max Length Calculation:
max_length
keeps track of the length of the longest substring without repeating characters as the algorithm moves forward.