タイトル説明
基本的な考え方
スライディングウィンドウ
- 使用
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;
}