Title Description
The basic idea
Sliding window
- Use
HashSet
to achieve - Use
HashMap
to achieve
Java implementation
- HashSet
public static int lengthOfLongestSubstring3(String s) {
if(s == null || s.length() == 0) return 0;
HashSet<Character> set = new HashSet<>();
int res = 0;
for(int i = 0, j = 0; i < s.length(); i ++ ) {
if(set.contains(s.charAt(i))) {
set.remove(s.charAt(j));
j++;
i--;
} else {
set.add(s.charAt(i));
res = Math.max(res, i - j + 1);
}
}
return res;
}
- HashMap
public static int lengthOfLongestSubstring2(String s) {
if( s == null || s.length() == 0) return 0;
HashSet<Character> set = new HashSet<>();
int res = 0;
for(int i = 0, j = 0; i < s.length(); i++) {
if(set.contains(s.charAt(i))) {
set.remove(s.charAt(j));
j++;
} else {
set.add(s.charAt(i));
res = Math.max(res, i - j + 1);
}
}
return res;
}