子串
# 和为k的子数组
class Solution {
public int subarraySum(int[] nums, int k) {
int count = 0;
for(int i = 0; i < nums.length; i++){
int sum = 0;
for(int j = i; j >=0; j--){
sum+= nums[j];
if(sum == k){
count++;
}
}
}
return count;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# 滑动窗口最大值
class Solution {
public int[] maxSlidingWindow(int[] nums, int k) {
if(nums.length == 0 || k == 0) return new int[0];
Deque<Integer> deque = new LinkedList<>();
int[] res = new int[nums.length - k + 1];
for(int j = 0, i = 1 - k; j < nums.length; i++, j++) {
// 删除 deque 中对应的 nums[i-1]
if(i > 0 && deque.peekFirst() == nums[i - 1])
deque.removeFirst();
// 保持 deque 递减
while(!deque.isEmpty() && deque.peekLast() < nums[j])
deque.removeLast();
deque.addLast(nums[j]);
// 记录窗口最大值
if(i >= 0)
res[i] = deque.peekFirst();
}
return res;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# 最小覆盖子串
class Solution {
public String minWindow(String s, String t) {
Map<Character,Integer> windows = new HashMap<>();
Map<Character,Integer> need = new HashMap<>();
for(int i = 0; i< t.length(); i++){
need.put(t.charAt(i), need.getOrDefault(t.charAt(i), 0)+1);
}
int left = 0;
int right = 0;
int valdate = 0;
int start = 0;
int len = Integer.MAX_VALUE;
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))){
valdate++;
}
}
while(valdate == need.size()){
if(right- left < len){
start = left;
len = right-left;
}
char d = s.charAt(left);
left++;
if(need.containsKey(d)){
if(windows.get(d).equals(need.get(d))){
valdate--;
}
windows.put(d, windows.getOrDefault(d, 0)-1);
}
}
}
return len == Integer.MAX_VALUE? "": s.substring(start, start+len);
}
}
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
38
39
40
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
38
39
40
上次更新: 2024/03/26, 9:03:00