0%

Longest Substring Without Repeating Characters

Question

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

Example 1:

Input: “abcabcbb”
Output: 3
Explanation: The answer is “abc”, with the length of 3.

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/*
@param: s input string;
@return: int, longest length of substring;
Algorithm: two pointers, hashset, check repeat in substring(i,j), if no repeat,j++, else i++;
follow up hashset could be replaced by char[256];
*/
public int lengthOfLongestSubstring(String s) {
if (s.length() == 0) return 0;

Set<Character> set = new HashSet<>();
int ans = Integer.MIN_VALUE;
for (int i = 0, j = 0; i < s.length(); i++) {
while (j < s.length()) {
if (!set.contains(s.charAt(j))) {
set.add(s.charAt(j));
j++;
ans = Math.max(ans, j-i);
}else break;
}
set.remove(s.charAt(i));
}
return ans;
}