-
-
Notifications
You must be signed in to change notification settings - Fork 243
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
找出字符串中第一个匹配项的下标 #447
Comments
顺手记 var strStr = function(haystack, needle) {
const m = haystack.length, n = needle.length;
if (n === 0) {
return 0;
}
const next = new Array(n).fill(0);
// 处理 needle 数组得到 next 数组,第一个循环会保持 j 一直在满足needle[i]
// ==needle[j]的位置
// next = aaaabbbbhgg -> 01230000000
// next = aaabbbaaabbb -> 012000123456
for (let i = 1, j = 0; i < n; i++) {
while (j > 0 && needle[i] !== needle[j]) {
j = next[j - 1];
}
if (needle[i] == needle[j]) {
j++;
}
next[i] = j;
}
// haystack 为 abababc ,needle 为ababc,
// next 为 00120
// 发现 i=4 时, needle 中的 j 只需回退到2, 如此时间复杂度减小了
for (let i = 0, j = 0; i < m; i++) {
while (j > 0 && haystack[i] != needle[j]) {
j = next[j - 1];
}
if (haystack[i] == needle[j]) {
j++;
}
if (j === n) {
return i - n + 1;
}
}
return -1;
}; |
|
/**
* @param {string} haystack
* @param {string} needle
* @return {number}
*/
var strStr = function (haystack, needle) {
let h1 = 0
let n1 = 0
while (h1 < haystack.length && n1 < needle.length) {
if (haystack[h1 + n1] !== needle[n1]) {
h1++
n1 = 0
} else {
n1++
}
}
return n1 === needle.length ? h1 : -1
};
|
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
No description provided.
The text was updated successfully, but these errors were encountered: