File tree Expand file tree Collapse file tree 1 file changed +32
-0
lines changed Expand file tree Collapse file tree 1 file changed +32
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * @param {string } haystack
3
+ * @param {string } needle
4
+ * @return {number }
5
+ */
6
+ const strStr = function ( a , b ) {
7
+ if ( b === '' ) return 0
8
+ if ( a . length < b . length ) return - 1
9
+ if ( a . length === b . length ) return a === b ? 0 : - 1
10
+ const m = a . length , n = b . length
11
+ const fail = Array ( n ) . fill ( - 1 )
12
+ // DFA
13
+ for ( let i = 1 ; i < n ; i ++ ) {
14
+ let j = fail [ i - 1 ]
15
+ while ( j !== - 1 && b [ j + 1 ] !== b [ i ] ) {
16
+ j = fail [ j ]
17
+ }
18
+ if ( b [ j + 1 ] === b [ i ] ) fail [ i ] = j + 1
19
+ }
20
+ let pos = - 1
21
+ for ( let i = 0 ; i < m ; i ++ ) {
22
+ while ( pos !== - 1 && a [ i ] !== b [ pos + 1 ] ) pos = fail [ pos ]
23
+ if ( a [ i ] === b [ pos + 1 ] ) {
24
+ pos ++
25
+ if ( pos === n - 1 ) return i - n + 1
26
+ }
27
+ }
28
+ return - 1
29
+ } ;
30
+
31
+ // another
32
+
1
33
/**
2
34
* @param {string } haystack
3
35
* @param {string } needle
You can’t perform that action at this time.
0 commit comments