Skip to content

Commit 1310476

Browse files
committed
Time: 64 ms (16.28%), Space: 44.6 MB (5.19%) - LeetHub
1 parent f7bf326 commit 1310476

File tree

1 file changed

+27
-27
lines changed

1 file changed

+27
-27
lines changed

0028-find-the-index-of-the-first-occurrence-in-a-string/0028-find-the-index-of-the-first-occurrence-in-a-string.js

Lines changed: 27 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -3,33 +3,6 @@
33
* @param {string} needle
44
* @return {number}
55
*/
6-
function LPSArrForPattern(pat) {
7-
let [patLength, pre, suf] = [pat.length, 0, 1];
8-
if (patLength === 0) return 0;
9-
10-
let lpsArr = new Array(patLength).fill(0);
11-
12-
while (suf < patLength) {
13-
// match
14-
if (pat[pre] === pat[suf]) {
15-
lpsArr[suf] = pre + 1;
16-
pre++;
17-
suf++;
18-
} else {
19-
// mismatch and pre at 0
20-
if (pre === 0) {
21-
lpsArr[suf] = 0;
22-
suf++;
23-
} else {
24-
// mismatch and pre not at 0
25-
pre = lpsArr[pre - 1];
26-
}
27-
}
28-
}
29-
30-
return lpsArr;
31-
}
32-
336
var strStr = function (str, pat) {
347
let [strLength, patLength, first, second] = [str.length, pat.length, 0, 0];
358

@@ -52,4 +25,31 @@ var strStr = function (str, pat) {
5225

5326
if (second === patLength) return first - second;
5427
return -1;
28+
29+
function LPSArrForPattern(pat) {
30+
let [pre, suf] = [0, 1];
31+
if (patLength === 0) return 0;
32+
33+
let lpsArr = new Array(patLength).fill(0);
34+
35+
while (suf < patLength) {
36+
// match
37+
if (pat[pre] === pat[suf]) {
38+
lpsArr[suf] = pre + 1;
39+
pre++;
40+
suf++;
41+
} else {
42+
// mismatch and pre at 0
43+
if (pre === 0) {
44+
lpsArr[suf] = 0;
45+
suf++;
46+
} else {
47+
// mismatch and pre not at 0
48+
pre = lpsArr[pre - 1];
49+
}
50+
}
51+
}
52+
53+
return lpsArr;
54+
}
5555
};

0 commit comments

Comments
 (0)