滑动窗口
# 无重复最长子串
class Solution {
public int lengthOfLongestSubstring(String s) {
if(s == null){
return 0;
}
int l = 0;
int r = 0;
int res = 0;
Set<Character> set = new HashSet<>();
while(r< s.length()){
char c = s.charAt(r);
while(set.contains(c)){
char d = s.charAt(l);
set.remove(d);
l++;
}
set.add(c);
res = Math.max(res, set.size());
r++;
}
return res;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# 字符串的所以字母异位词
class Solution {
public List<Integer> findAnagrams(String s, String p) {
Map<Character, Integer> windows = new HashMap<>();
Map<Character, Integer> need = new HashMap<>();
for(int i = 0; i < p.length(); i++){
need.put(p.charAt(i), need.getOrDefault(p.charAt(i), 0)+1);
}
int left = 0;
int right = 0;
int vaildate = 0;
List<Integer> res = new ArrayList<>();
while(right < s.length()){
char c = s.charAt(right);
right++;
if(need.containsKey(c)){
windows.put(c, windows.getOrDefault(c,0)+1);
if(windows.get(c).equals(need.get(c))){
vaildate++;
}
}
while(right -left >= p.length()){
if(vaildate == need.size()){
res.add(left);
}
char d = s.charAt(left);
left++;
if(need.containsKey(d)){
if(windows.get(d).equals(need.get(d))){
vaildate--;
}
windows.put(d, windows.getOrDefault(d,0)-1);
}
}
}
return res;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
上次更新: 2024/03/26, 9:03:00