Skip to content

Commit e22a08e

Browse files
committedJan 18, 2020
add
1 parent 822cb30 commit e22a08e

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed
 
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
/**
2+
* 滑动窗口解法,双指针
3+
*/
4+
class Solution {
5+
public List<Integer> findAnagrams(String s, String p) {
6+
if(s == null || s.length() == 0) return new ArrayList<>();
7+
List<Integer> res = new ArrayList<>();
8+
int[] needs = new int[26];
9+
int[] windows = new int[26];
10+
int left = 0 , right = 0 , total = p.length();
11+
12+
for(char a : p.toCharArray()) {
13+
needs[a - 'a']++;
14+
}
15+
16+
while(right < s.length()) {
17+
char now = s.charAt(right);
18+
if(needs[now - 'a'] > 0) {
19+
windows[now - 'a']++;
20+
if(windows[now - 'a'] <= needs[now - 'a']) {
21+
total -= 1;
22+
}
23+
}
24+
while(total == 0) {
25+
if(right-left+1 == p.length()){
26+
res.add(left);
27+
}
28+
char c = s.charAt(left);
29+
if(needs[c - 'a'] > 0) {
30+
windows[c - 'a']--;
31+
if(windows[c - 'a'] < needs[c - 'a']) {
32+
total++;
33+
}
34+
}
35+
left++;
36+
}
37+
right++;
38+
}
39+
return res;
40+
}
41+
}

0 commit comments

Comments
 (0)
Please sign in to comment.