File tree Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Expand file tree Collapse file tree 1 file changed +41
-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 ( haystack , needle ) {
7+ const m = haystack . length , n = needle . length
8+
9+ const lps = process ( needle )
10+ for ( let j = 0 , i = 0 ; i < m ; i ++ ) {
11+ while ( j > 0 && haystack [ i ] !== needle [ j ] ) {
12+ j = lps [ j - 1 ]
13+ }
14+ if ( haystack [ i ] === needle [ j ] ) {
15+ j ++
16+ if ( j === n ) {
17+ return i - n + 1
18+ }
19+ }
20+ }
21+ return - 1
22+
23+ function process ( s ) {
24+ const n = s . length
25+ const lps = Array ( n ) . fill ( 0 )
26+ for ( let len = 0 , i = 1 ; i < n ; i ++ ) {
27+ while ( len > 0 && s [ i ] !== s [ len ] ) {
28+ len = lps [ len - 1 ]
29+ }
30+ if ( s [ i ] === s [ len ] ) {
31+ len ++
32+ lps [ i ] = len
33+ }
34+ }
35+
36+ return lps
37+ }
38+ } ;
39+
40+ // another
41+
142/**
243 * @param {string } haystack
344 * @param {string } needle
You can’t perform that action at this time.
0 commit comments