To solve this problem, we need to find the length of the longest substring without repeating characters in a given string. The optimal approach to this problem is using the sliding window technique combined with a hash set to efficiently track characters in the current window.
Approach
- Sliding Window Technique: We use two pointers (
leftandright) to represent the current window of characters being checked. Therightpointer expands the window by moving to the right, while theleftpointer contracts the window when a duplicate character is encountered. - Hash Set: A set is used to keep track of characters in the current window. This allows O(1) time complexity for checking the presence of a character and adding/removing characters.
- Update Maximum Length: For each valid window (without duplicates), we update the maximum length of the window if it is larger than the current maximum.
Solution Code
def lengthOfLongestSubstring(s: str) -> int:
char_set = set()
left = 0
max_len = 0
for right in range(len(s)):
# If current character is in the set, move left pointer to remove duplicates
while s[right] in char_set:
char_set.remove(s[left])
left += 1
# Add current character to the set
char_set.add(s[right])
# Update max length
current_len = right - left + 1
if current_len > max_len:
max_len = current_len
return max_len
Explanation
- Initialization: We start with
leftpointer at 0,max_lenat 0, and an empty setchar_set. - Expanding the Window: The
rightpointer iterates over each character in the string. For each character:- If the character is already in the set, we move the
leftpointer to the right until the duplicate character is removed from the set. - We add the current character to the set.
- We calculate the length of the current window (
right - left +1) and updatemax_lenif this length is greater than the currentmax_len.
- If the character is already in the set, we move the
- Result: The
max_lenvariable holds the length of the longest substring without repeating characters.
This approach ensures that each character is processed at most twice (once by the right pointer and once by the left pointer), leading to an O(n) time complexity, where n is the length of the string. The space complexity is O(k), where k is the number of distinct characters in the string. This is efficient and handles all edge cases, including empty strings and strings with all unique characters.


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