Description

Given a string s, find the length of the longest substring without duplicate characters.

Example 1:

1
2
3
Input: s = "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.

Example 2:
1
2
3
Input: s = "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.

Example 3:
1
2
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.

1
2
3
4
Constraints:

0 <= s.length <= 5 * 104
s consists of English letters, digits, symbols and spaces.

Approach: Sliding Window

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public int lengthOfLongestSubstring(String s) {
int n = s.length();
Set<Character> set = new HashSet<>();
int ans = 0, i = 0, j = 0;
while (i < n && j < n) {
if (!set.contains(s.charAt(j))) {
set.add(s.charAt(j++));
ans = Math.max(ans, j - i);
} else {
set.remove(s.charAt(i++));
}
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public int lengthOfLongestSubstring(String s) {
int start = 0;
int[] lastIndex = new int[128]; // assuming ASCII characters
for(int i=0; i<128; i++){
lastIndex[i] = -1; // initialize all characters' last index as -1
}
int max = 0;
for(int end=0; end<s.length(); end++){
char c = s.charAt(end);
if(lastIndex[c] >= start) start = lastIndex[c] + 1;
lastIndex[c] = end;
if(end - start + 1 > max) max = end - start + 1;
}
return max;
}
}