Skip to content

Commit 56312e3

Browse files
committed
滑动窗口法,0438,找到字符串中所有字母异位词
滑动窗口
1 parent 2107a9c commit 56312e3

File tree

3 files changed

+61
-1
lines changed

3 files changed

+61
-1
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -109,6 +109,7 @@
109109
|0415|字符串相加|简单||
110110
|[0425](https://leetcode-cn.com/tag/sliding-window/)|替换后的最长重复字符|中等|[sliding window](sliding_window)|
111111
|0437|路径总和 III|简单||
112+
|[0438](https://leetcode-cn.com/problems/find-all-anagrams-in-a-string/)|找到字符串中所有字母异位词|中等|[sliding window](sliding_window)|
112113
|0441|排列硬币|简单||
113114
|0447|回旋镖的数量|简单||
114115
|0448|找到所有数组中消失的数字|简单||

sliding_window/Lc0438Solution.java

+58
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
package sliding_window;
2+
3+
import java.util.ArrayList;
4+
import java.util.Collections;
5+
import java.util.List;
6+
7+
public class Lc0438Solution {
8+
public List<Integer> findAnagrams(String s, String p) {
9+
if (s == null || s.length() < p.length()) {
10+
return Collections.emptyList();
11+
}
12+
int[] windows = new int[26];
13+
int[] need = new int[26];
14+
for (int i = 0; i < p.length(); i++) {
15+
need[p.charAt(i)-'a']++;
16+
windows[s.charAt(i)-'a']++;
17+
}
18+
int count = 0;
19+
for (int i = 0; i < 26; i++) {
20+
if (windows[i] == need[i]) {
21+
count++;
22+
}
23+
}
24+
List<Integer> ret = new ArrayList<>();
25+
if (count == 26) {
26+
ret.add(0);
27+
}
28+
int pLen = p.length();
29+
for (int i = 0; i < s.length() - pLen; i++) {
30+
int l = s.charAt(i) - 'a', r = s.charAt(i + pLen) - 'a';
31+
windows[r]++;
32+
if (windows[r] == need[r]) {
33+
count++;
34+
} else if (windows[r] == need[r] + 1) {
35+
count--;
36+
}
37+
// 顺序很重要
38+
windows[l]--;
39+
if (windows[l] == need[l]) {
40+
count++;
41+
} else if (windows[l] == need[l] - 1) {
42+
count--;
43+
}
44+
if (count == 26) {
45+
// emmm
46+
ret.add(i+1);
47+
}
48+
}
49+
return ret;
50+
}
51+
52+
public static void main(String[] args) {
53+
Lc0438Solution solution = new Lc0438Solution();
54+
String s = "cbaebabacd";
55+
String p = "abc";
56+
System.out.println(solution.findAnagrams(s, p));
57+
}
58+
}

sliding_window/README.md

+2-1
Original file line numberDiff line numberDiff line change
@@ -6,4 +6,5 @@
66
|[0395](https://leetcode-cn.com/problems/longest-substring-with-at-least-k-repeating-characters/)|至少有K个重复字符的最长子串|中等||
77
|[0425](https://leetcode-cn.com/tag/sliding-window/)|替换后的最长重复字符|中等||
88
|[0159](https://leetcode-cn.com/problems/longest-substring-with-at-most-two-distinct-characters/)|至多包含两个不同字符的最长子串|中等||
9-
|[0340](https://leetcode-cn.com/problems/longest-substring-with-at-most-k-distinct-characters/)|至多包含 K 个不同字符的最长子串|中等||
9+
|[0340](https://leetcode-cn.com/problems/longest-substring-with-at-most-k-distinct-characters/)|至多包含 K 个不同字符的最长子串|中等||
10+
|[0438](https://leetcode-cn.com/problems/find-all-anagrams-in-a-string/)|找到字符串中所有字母异位词|中等||

0 commit comments

Comments
 (0)