滑动窗口最大值

img

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
public int[] maxSlidingWindow(int[] nums, int k) {
int l = nums.length;
if (nums == null || l < 2) {
return nums;
}
LinkedList<Integer> list = new LinkedList();
int[] rlt = new int[l - k + 1];
for (int i = 0; i < l; i++) {
while (!list.isEmpty() && nums[list.peekLast()] <= nums[i]) {
list.pollLast();
}
list.addLast(i);
//窗口满了
if (i >= k && i - k == list.peek()) {
list.poll();
}
if (i - k + 1 >= 0) {
rlt[i - k + 1] = nums[list.peek()];
}
}
return rlt;
}
}

无重复字符的最长子串

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public int lengthOfLongestSubstring(String s) {
int[] last = new int[128];
for (int i = 0; i < 128; i++) {
last[i] = -1;
}
int n = s.length();
int res = 0;
int start = 0;
for (int i = 0; i < n; i++) {
int index = s.charAt(i);
start = Math.max(start, last[index] + 1);
res = Math.max(res, i - start + 1);
last[index] = i;
System.out.println("i:"+i+" start:"+start+" res:"+res);
}
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
38
39
40
41
class Solution {
public List<Integer> findAnagrams(String s, String p) {
if (s == null || s.length() == 0 || s.length() < p.length()) {
return new ArrayList<>();
}
List<Integer> list = new ArrayList<>();
// 目标串数组
int[] pArr = new int[26];
// 窗口数组
int[] sArr = new int[26];
for (int i = 0; i < p.length(); i++) {
pArr[p.charAt(i) - 'a']++;
sArr[s.charAt(i) - 'a']++;
}
int i = 0, j = p.length();
while (j < s.length()) {
if (isSame(pArr, sArr)) {
list.add(i);
}
//左边减
sArr[s.charAt(i) - 'a']--;
i++;
//右边加
sArr[s.charAt(j) - 'a']++;
j++;
}
if (isSame(pArr, sArr)) {
list.add(i);
}
return list;
}

private boolean isSame(int[] arr1, int[] arr2) {
for (int i = 0; i < arr1.length; i++) {
if (arr1[i] != arr2[i]) {
return false;
}
}
return true;
}
}