mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 16:54:50 +08:00
提供JavaScript版本的《实现strStr()》
This commit is contained in:
@ -808,7 +808,93 @@ func strStr(haystack string, needle string) int {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
JavaScript版本
|
||||||
|
|
||||||
|
> 前缀表统一减一
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
/**
|
||||||
|
* @param {string} haystack
|
||||||
|
* @param {string} needle
|
||||||
|
* @return {number}
|
||||||
|
*/
|
||||||
|
var strStr = function (haystack, needle) {
|
||||||
|
if (needle.length === 0)
|
||||||
|
return 0;
|
||||||
|
|
||||||
|
const getNext = (needle) => {
|
||||||
|
let next = [];
|
||||||
|
let j = -1;
|
||||||
|
next.push(j);
|
||||||
|
|
||||||
|
for (let i = 1; i < needle.length; ++i) {
|
||||||
|
while (j >= 0 && needle[i] !== needle[j + 1])
|
||||||
|
j = next[j];
|
||||||
|
if (needle[i] === needle[j + 1])
|
||||||
|
j++;
|
||||||
|
next.push(j);
|
||||||
|
}
|
||||||
|
|
||||||
|
return next;
|
||||||
|
}
|
||||||
|
|
||||||
|
let next = getNext(needle);
|
||||||
|
let j = -1;
|
||||||
|
for (let i = 0; i < haystack.length; ++i) {
|
||||||
|
while (j >= 0 && haystack[i] !== needle[j + 1])
|
||||||
|
j = next[j];
|
||||||
|
if (haystack[i] === needle[j + 1])
|
||||||
|
j++;
|
||||||
|
if (j === needle.length - 1)
|
||||||
|
return (i - needle.length + 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
return -1;
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
> 前缀表统一不减一
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
/**
|
||||||
|
* @param {string} haystack
|
||||||
|
* @param {string} needle
|
||||||
|
* @return {number}
|
||||||
|
*/
|
||||||
|
var strStr = function (haystack, needle) {
|
||||||
|
if (needle.length === 0)
|
||||||
|
return 0;
|
||||||
|
|
||||||
|
const getNext = (needle) => {
|
||||||
|
let next = [];
|
||||||
|
let j = 0;
|
||||||
|
next.push(j);
|
||||||
|
|
||||||
|
for (let i = 1; i < needle.length; ++i) {
|
||||||
|
while (j > 0 && needle[i] !== needle[j])
|
||||||
|
j = next[j - 1];
|
||||||
|
if (needle[i] === needle[j])
|
||||||
|
j++;
|
||||||
|
next.push(j);
|
||||||
|
}
|
||||||
|
|
||||||
|
return next;
|
||||||
|
}
|
||||||
|
|
||||||
|
let next = getNext(needle);
|
||||||
|
let j = 0;
|
||||||
|
for (let i = 0; i < haystack.length; ++i) {
|
||||||
|
while (j > 0 && haystack[i] !== needle[j])
|
||||||
|
j = next[j - 1];
|
||||||
|
if (haystack[i] === needle[j])
|
||||||
|
j++;
|
||||||
|
if (j === needle.length)
|
||||||
|
return (i - needle.length + 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
return -1;
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user