一个字符串中是否出现某串字符,出现的话返回索引
Sunny-117 opened this issue · comments
Sunny commented
beary commented
kmp
let p = " " + "abc";
let s = " " + "cdeeeffabcsssabc";
const n = p.length - 1;
const m = s.length - 1;
// n相当于pattern串,str1
// str2 相当于匹配串
const ne = new Array(n).fill(0);
// 结果存储res
const res = [];
// 获取next数组
for (let i = 2, j = 0; i <= n; i++) {
while (j && p[i] !== p[j + 1]) j = ne[j];
if (p[i] === p[j + 1]) j++;
ne[i] = j;
}
// 开始进行匹配
for (let i = 1, j = 0; i <= m; i++) {
while (j && s[i] !== p[j + 1]) j = ne[j];
if (s[i] === p[j + 1]) j++;
if (j === n) {
res.push(i - n);
j = ne[j];
}
}
console.log(res);
fencer commented
function getIndexOf(str, sub) {
const reg = new RegExp(sub, 'g');
let result = -1;
str.replaceAll(reg, (_, index) => { if (result === -1 && index !== void 0) result = index });
return result;
}