3. Longest Substring Without Repeating Characters ๐
Last updated
Was this helpful?
Last updated
Was this helpful?
Difficulty: Medium
- Tags: Hash Table
, String
, Sliding Window
Given a string s
, find the length of the longest substring without repeating characters.
๐น Example 1:
Input:
Output:
Explanation: The answer is "abc", with the length of 3.
๐น Example 2:
Input:
Output:
Explanation: The answer is "b", with the length of 1.
๐น Example 3:
Input:
Output:
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.
0 <= s.length <= 5 * 10^4
s
consists of English letters, digits, symbols, and spaces.
To solve this problem, we can use the Sliding Window approach:
Use a Set: Utilize a HashSet
to track characters in the current window.
Expand and Shrink the Window:
Expand the right
pointer to include characters in the window.
If a duplicate character is found, shrink the window from the left until the window contains no duplicate characters.
Update the Result:
Keep track of the maximum length of valid substrings.
O(n): Each character is processed at most twice (once added, once removed).
O(min(n, m)): Space used by the HashSet
, bounded by the size of the input n
and the size of the character set m
.
You can find the full solution .