Given a string s
, find the length of the longest
Example 1:
Input: s = "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.
Example 2:
Input: s = "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.
Example 3:
Input: s = "pwwkew"
Output: 3
Explanation: The answer is "wke", with the length of 3.
Notice that the answer must be a substring, "pwke" is a subsequence and not a substring.
Constraints:
0 <= s.length <= 5 * 104
s
consists of English letters, digits, symbols and spaces.
SOLUTION
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
sSet: Set[T] = set()
l: int = 0
result: int = 0
for r in range(len(s)):
while s[r] in sSet:
sSet.remove(s[l])
l += 1
sSet.add(s[r])
result = max(result, r-l+1)
return result
Time Complexity: O(n)
Space Complexity:O(n)
How it works:
- The function
lengthOfLongestSubstring
takes a string as input and returns the length of the longest substring without repeating characters. - A set is created to store the characters in the substring.
- Two pointers are initialized:
l
is the left pointer, andr
is the right pointer. - The variable
result
is initialized to 0. - The loop iterates over the characters in the string.
- If the current character is already in the set, the leftmost character from the set is removed.
- The current character is added to the set.
- The result is updated to the maximum of the result and the length of the substring from
l
tor
. - The right pointer is incremented.
- The loop continues until the right pointer reaches the end of the string.
- The function returns the result.
Comments
Post a Comment