File tree 1 file changed +42
-0
lines changed
1 file changed +42
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * @param {string } s
3
+ * @param {string } p
4
+ * @return {number[] }
5
+ */
6
+ var findAnagrams = function ( s , p ) {
7
+ const charMap = new Map ( ) ;
8
+ let matches = 0 ;
9
+ const matchIdx = [ ] ;
10
+
11
+ for ( const char of p ) {
12
+ const charCount = charMap . get ( char ) || 0 ;
13
+ charMap . set ( char , charCount + 1 ) ;
14
+ }
15
+
16
+ let leftWindow = 0 ;
17
+ for ( let rightWindow = 0 ; rightWindow < s . length ; rightWindow ++ ) {
18
+ const rightChar = s [ rightWindow ] ;
19
+ if ( charMap . has ( rightChar ) ) {
20
+ const rightCharCount = charMap . get ( rightChar ) ;
21
+ charMap . set ( rightChar , rightCharCount - 1 ) ;
22
+ if ( charMap . get ( rightChar ) === 0 ) {
23
+ matches ++ ;
24
+ }
25
+ }
26
+ if ( rightWindow >= p . length ) {
27
+ const leftChar = s [ leftWindow ] ;
28
+ if ( charMap . has ( leftChar ) ) {
29
+ const leftCharCount = charMap . get ( leftChar ) ;
30
+ charMap . set ( leftChar , leftCharCount + 1 ) ;
31
+ if ( leftCharCount === 0 ) {
32
+ matches -- ;
33
+ }
34
+ }
35
+ leftWindow ++ ;
36
+ }
37
+ if ( matches === charMap . size ) {
38
+ matchIdx . push ( leftWindow ) ;
39
+ }
40
+ }
41
+ return matchIdx ;
42
+ } ;
You can’t perform that action at this time.
0 commit comments