题目描述
基本思路
滑动窗口
- 利用
HashSet
实现 - 利用
HashMap
实现
Java实现
- 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;
}