Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

一个字符串中是否出现某串字符,出现的话返回索引 #257

Open
Sunny-117 opened this issue Nov 4, 2022 · 2 comments
Open

Comments

@Sunny-117
Copy link
Owner

No description provided.

@bearki99
Copy link

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-yd
Copy link

fencer-yd commented Jun 5, 2023

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;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants