Skip to content

Commit be11eb4

Browse files
committed
Time: 56 ms (38.25%), Space: 42.3 MB (20.02%) - LeetHub
1 parent 2b02237 commit be11eb4

File tree

1 file changed

+11
-44
lines changed

1 file changed

+11
-44
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: 11 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -3,53 +3,20 @@
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];
6+
var strStr = function (haystack, needle) {
7+
if (needle.length === 0) return 0;
8+
  if (haystack.length < needle.length) return -1;
9+
10+
for (let i = 0; i < haystack.length; i++) {
11+
let isMatch = true;
12+
for (let j = 0; j < needle.length; j++) {
13+
if (haystack[i + j] !== needle[j]) {
14+
isMatch = false;
15+
break;
2616
}
2717
}
28-
}
29-
30-
return lpsArr;
31-
}
3218

33-
var strStr = function (str, pat) {
34-
let [strLength, patLength, first, second] = [str.length, pat.length, 0, 0];
35-
36-
while (first < strLength && second < patLength) {
37-
// match
38-
if (str[first] === pat[second]) {
39-
first++;
40-
second++;
41-
} else {
42-
// mismatch and pre at 0
43-
if (second === 0) {
44-
first++;
45-
} else {
46-
// mismatch and pre not at 0
47-
let lpsArr = LPSArrForPattern(pat);
48-
second = lpsArr[second - 1];
49-
}
50-
}
19+
if (isMatch) return i;
5120
}
52-
53-
if (second === patLength) return first - second;
5421
return -1;
5522
};

0 commit comments

Comments
 (0)