3. Longest Substring Without Repeating Characters ๐
Difficulty: Medium
- Tags: Hash Table
, String
, Sliding Window
Problem Statement ๐
Given a string s
, find the length of the longest substring without repeating characters.
Examples ๐
๐น 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.
Constraints โ๏ธ
0 <= s.length <= 5 * 10^4
s
consists of English letters, digits, symbols, and spaces.
Solution ๐ก
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.
Java Solution
Time Complexity โณ
O(n): Each character is processed at most twice (once added, once removed).
Space Complexity ๐พ
O(min(n, m)): Space used by the
HashSet
, bounded by the size of the inputn
and the size of the character setm
.
You can find the full solution here.
Last updated