To solve this problem, we need to find the length of the longest substring without repeating characters in a given string. The optimal approach involves using a sliding window technique combined with a data structure to track the last occurrence of each character, ensuring an efficient solution with linear time complexity.
Approach
The sliding window technique uses two pointers (left and right) to represent the current substring being evaluated. We also maintain a data structure to keep track of the last index of each character encountered. Here's the detailed breakdown:
-
Initialization:
- A list
last_occurrence(size 128 for ASCII characters) to store the last index of each character. leftpointer starts at 0 (beginning of the string).max_lento keep track of the length of the longest substring found.
- A list
-
Iterate with
rightpointer:- For each character at position
right, check if it has been seen before and if its last occurrence is within the current window (i.e., >=left). - If it has, move the
leftpointer to the position right after the last occurrence of the current character to exclude the duplicate. - Update the
last_occurrenceof the current character toright. - Calculate the length of the current window (
right - left +1) and updatemax_lenif this length is greater than the currentmax_len.
- For each character at position
This approach ensures that each character is processed exactly once, leading to an O(n) time complexity, where n is the length of the string. The space complexity is O(1) since the size of last_occurrence is fixed (128 characters).
Solution Code
def lengthOfLongestSubstring(s: str) -> int:
last_occurrence = [-1] * 128 # Covers all ASCII characters
left = 0
max_len = 0
for right in range(len(s)):
char_code = ord(s[right])
if last_occurrence[char_code] >= left:
left = last_occurrence[char_code] + 1
last_occurrence[char_code] = right
max_len = max(max_len, right - left + 1)
return max_len
Explanation
- Sliding Window: The window is defined by
leftandrightpointers. Asrightmoves forward, we expand the window. If a duplicate is found within the window,leftmoves to shrink the window to exclude the duplicate. - Last Occurrence Tracking: The
last_occurrencelist allows us to quickly check if a character has been seen and where it was last seen, which helps in adjusting the window efficiently. - Efficiency: This method runs in O(n) time because each character is processed once, and each pointer (
leftandright) moves forward only, never backward. The space used is constant (O(1)) since the list size is fixed.
This solution efficiently handles all edge cases, including empty strings, single characters, and strings with all unique characters. It is optimal and widely used for this problem.


作者声明:本文包含人工智能生成内容。