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

找出字符串中第一个匹配项的下标 #447

Open
Pcjmy opened this issue Feb 3, 2023 · 3 comments
Open

找出字符串中第一个匹配项的下标 #447

Pcjmy opened this issue Feb 3, 2023 · 3 comments

Comments

@Pcjmy
Copy link
Contributor

Pcjmy commented Feb 3, 2023

No description provided.

@z1the3
Copy link

z1the3 commented Apr 25, 2023

顺手记

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

@jianqi-jin
Copy link

class Solution:
    def strStr(self, haystack: str, needle: str) -> int:
        for i in range(len(haystack)):
            if haystack[i:i+len(needle)] == needle:
                return i
        return -1
                
        

@coderTopu
Copy link

/**
 * @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
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants