Sunny-117 / js-challenges

✨✨✨ Challenge your JavaScript programming limits step by step

Home Page:https://juejin.cn/column/7244788137410560055

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

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

Pcjmy opened this issue · comments

commented
commented

顺手记

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;
};
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
                
        
/**
 * @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
};