File tree 1 file changed +41
-0
lines changed
1 file changed +41
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments