28. 实现 strStr()
题目链接:https://leetcode.cn/problems/find-the-index-of-the-first-occurrence-in-a-string/
解题思路
1.KMP
代码
/**
* @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;
};
459. 重复的子字符串
题目链接:https://leetcode.cn/problems/repeated-substring-pattern/
解题思路
1.KMP
代码
/**
* @param {string} s
* @return {boolean}
*/
var repeatedSubstringPattern = function (s) {
if (s.length === 0) return false;
const getNext = (s) => {
let next = [];
let j = -1;
next.push(j);
for (let i = 1; i < s.length; ++i) {
while (j >= 0 && s[i] !== s[j + 1]) j = next[j];
if (s[i] === s[j + 1]) j++;
next.push(j);
}
return next;
};
let next = getNext(s);
if (
next[next.length - 1] !== -1 &&
s.length % (s.length - (next[next.length - 1] + 1)) === 0
)
return true;
return false;
};