JavaScript 版本KMP
https://leetcode.cn/problems/find-the-index-of-the-first-occurrence-in-a-string/solutions/732461/dai-ma-sui-xiang-lu-kmpsuan-fa-xiang-jie-mfbs/减1版本
```js
const generateNext = (str) => {
const arr = [-1];
let j = -1;
for (let i = 1; i < str.length; i++) {
const char = str;
while (j >= 0 && char != str) {
j = arr;
}
if (char == str) {
j++;
}
arr = j;
}
return arr;
};
/**
* @param {string} haystack
* @param {string} needle
* @Return {number}
*/
var strStr = function (haystack, needle) {
const next = generateNext(needle);
let j = -1;
for (let index = 0; index < haystack.length; index++) {
const char = haystack;
while (j >= 0 && char !== needle) {
j = next;
}
if (char == needle) {
j++;
}
if(j==needle.length-1){
return index-j
}
}
return -1
};
console.log(strStr("hello",'ll'));
```
不减1
```js
const generateNext = (str) => {
const arr = ;
let j = 0;
for (let i = 1; i < str.length; i++) {
const char = str;
while (j > 0 && char != str) {
j = arr;
}
if (char == str) {
j++;
}
arr = j;
}
return arr;
};
/**
* @param {string} haystack
* @param {string} needle
* @return {number}
*/
var strStr = function (haystack, needle) {
const next = generateNext(needle);
let j = 0;
for (let index = 0; index < haystack.length; index++) {
const char = haystack;
while (j > 0 && char !== needle) {
j = next;
}
if (char == needle) {
j++;
}
if (j == needle.length) {
return index - j+1;
}
}
return -1;
};
```
页:
[1]