var strStr = function (haystack, needle) {
let i=0,
j = 0;
let length = haystack.length;
let next = getNext(needle, new Array(needle.length).fill(0));
if (needle === "") {
return 0;
}
while(i<haystack.length&&j<needle.length) {
if (haystack[i] === needle[j]) {
i++;
j++;
console.log(haystack[i],needle[j])
} else {
if (j > 0) {
j = next[j - 1];
} else {
i++;
}
}
if (j === needle.length) {
return i - j ;
}
}
return -1;
};
console.log(strStr("mississippi", "issip"));
function getNext(str, next) {
let i,j = 0;
let length = str.length;
for (i = 1; i < length; i++) {
while (j > 0 && str[i] != str[j]) {
j = next[j - 1];
}
if (str[i] === str[j]) {
j++;
next[i] = j;
}
}
return next;
}
function getNext(str) {
let i = 1;
let j = 0;
let nextArr = new Array(str.length).fill(0);
nextArr[0] = str.length;
while(i<str.length) {
if(j==0 || str[i] === str[j]) {
j++;
i++;
nextArr[i] = j;
} else {
j=nextArr[j];
}
}
return nextArr;
}
function search(str1,str2) {
let i = 0;
let j = 0;
let next = getNext(str2);
console.log(next)
while(j<next[0]) {
if(str1[i] === str2[j]) {
i++;
j++;
if(j === next[0]) {
return i-j
}
} else if(j>0) {
j = next[j];
} else {
i++;
}
}
return false;
}
代码解释
issip的最大相同前后缀为 i
i is iss issi issip
0 0 0 1 0
mississippi
i
issip
00010
issip
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了