File tree 1 file changed +38
-0
lines changed
1 file changed +38
-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
+
7
+ const isAnagram = ( word , candidate ) => {
8
+ if ( word . length !== candidate . length ) return false ;
9
+
10
+ const charMap = { } ;
11
+ for ( let index = 0 ; index < word . length ; index ++ ) {
12
+ if ( word . indexOf ( candidate [ index ] ) < 0 ) {
13
+ return false ;
14
+ }
15
+ charMap [ word [ index ] ] = charMap [ word [ index ] ] ? charMap [ word [ index ] ] + 1 : 1 ;
16
+ charMap [ candidate [ index ] ] = charMap [ candidate [ index ] ] ? charMap [ candidate [ index ] ] - 1 : - 1 ;
17
+ }
18
+
19
+ return Object . keys ( charMap ) . every ( char => charMap [ char ] === 0 ) ;
20
+ } ;
21
+
22
+ const findAnagrams = ( s , p ) => {
23
+ const anagrams = { } ;
24
+ anagrams [ p ] = true ;
25
+
26
+ const answer = [ ] ;
27
+
28
+ const length = s . length - p . length + 1 ;
29
+ for ( let index = 0 ; index < length ; index ++ ) {
30
+ const candidate = s . slice ( index , index + p . length ) ;
31
+
32
+ if ( anagrams [ candidate ] === undefined ) anagrams [ candidate ] = isAnagram ( p , candidate ) ;
33
+
34
+ if ( anagrams [ candidate ] ) answer . push ( index ) ;
35
+ }
36
+
37
+ return answer ;
38
+ } ;
You can’t perform that action at this time.
0 commit comments