Given a string s, find the length of the longest substring without repeating characters.
Input: s = "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.
Input: s = "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.
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.
We need to find the longest window (substring) where all characters are unique. The key insight is to use a sliding window with:
This is a classic Sliding Window problem with:
Sliding Window with HashSet:
Initialize:
left = 0, right = 0 (window boundaries)charSet = empty set (tracks characters in current window)maxLength = 0Expand Window (move right):
right < s.length:
s[right] not in charSet:
s[right] to charSetmaxLength = max(maxLength, right - left + 1)right++s[left] from charSetleft++ (contract window)Return maxLength
1class Solution {
2 public int lengthOfLongestSubstring(String s) {
3 Set<Character> charSet = new HashSet<>();
4 int left = 0;
5 int maxLength = 0;
6
7 for (int right = 0; right < s.length(); right++) {
8 // Contract window while duplicate exists
9 while (charSet.contains(s.charAt(right))) {
10 charSet.remove(s.charAt(left));
11 left++;
12 }
13
14 // Add current character to window
15 charSet.add(s.charAt(right));
16
17 // Update max length
18 maxLength = Math.max(maxLength, right - left + 1);
19 }
20
21 return maxLength;
22 }
23}
24