Day09 | 字符串

46 阅读1分钟

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

O(m+n)

最长相同的前后缀的长度

跳转到next的长度下标位置

创建next数组

  • 初始化
  • 遍历
    • 前后缀相同
    • 前后缀不同
    • 更新next
def strStr(self, haystack: str, needle: str) -> int:
    next = [0] * len(needle)

    # create the next arr

    # suffix
    j = 1
    # prefix
    i = 0
    while j < len(needle):
        # if not
        while i > 0 and needle[i] != needle[j]:
            i = next[i-1]
        # if matched
        if needle[i] == needle[j]:
            i += 1
        next[j] = i
        j += 1

    if len(needle) == 0:
        return 0

    j = 0
    for i in range(len(haystack)):
        while j >= 1 and haystack[i] != needle[j]:
            j = next[j-1]
        if haystack[i] == needle[j]:
            j += 1
        if j == len(needle):
            return i - len(needle) + 1

    return -1

459. 重复的子字符串

用KMP的思路

def repeatedSubstringPattern(self, s: str) -> bool:
    next = [0] * len(s)
    if len(s) == 1:
        return False

    # create the next arr

    # suffix
    j = 1
    # prefix
    i = 0
    while j < len(s):
        # if not
        while i > 0 and s[i] != s[j]:
            i = next[i-1]
        # if matched
        if s[i] == s[j]:
            i += 1
        next[j] = i
        j += 1
    
    return next[-1] != 0 and len(s) % (len(s) - next[-1]) == 0

方法

  • 双指针
  • 反转
  • KMP