Intuition
The intuition behind the 3 solutions is to iteratively find the longest substring without repeating characters by maintaining a sliding window approach. We use two pointers (left and right) to represent the boundaries of the current substring. As we iterate through the string, we update the pointers and adjust the window to accommodate new unique characters and eliminate repeating characters.
Approach
- We use a set (
charSet) to keep track of unique characters in the current substring. - We maintain two pointers,
leftandright, to represent the boundaries of the current substring. - The
maxLengthvariable keeps track of the length of the longest substring encountered so far. - We iterate through the string using the
rightpointer. - If the current character is not in the set (
charSet), it means we have a new unique character. - We insert the character into the set and update the
maxLengthif necessary. - If the character is already present in the set, it indicates a repeating character within the current substring.
- In this case, we move the
leftpointer forward, removing characters from the set until the repeating character is no longer present. - We insert the current character into the set and continue the iteration.
- Finally, we return the
maxLengthas the length of the longest substring without repeating characters.
Complexity
- Time complexity:
- O(n)
- Space complexity:
- O(n)
Code
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
n = len(s)
maxLength = 0
charSet = set()
left = 0
for right in range(n):
if s[right] not in charSet:
charSet.add(s[right])
maxLength = max(maxLength, right - left + 1)
else:
while s[right] in charSet:
charSet.remove(s[left])
left += 1
charSet.add(s[right])
return maxLength
472

被折叠的 条评论
为什么被折叠?



