[LeetCode] 28. 实现 strStr()

Description

实现 strStr() 函数。

给你两个字符串 haystackneedle ,请你在 haystack 字符串中找出 needle 字符串出现的第一个位置(下标从 0 开始)。如果不存在,则返回  -1 。

说明:

当 needle 是空字符串时,我们应当返回什么值呢?这是一个在面试中很好的问题。

对于本题而言,当 needle 是空字符串时我们应当返回 0 。这与 C 语言的 strstr() 以及 Java 的 indexOf() 定义相符。

示例 1:

输入:haystack = "hello", needle = "ll"
输出:2

示例 2:

输入:haystack = "aaaaa", needle = "bba"
输出:-1

提示:

  • 1 <= haystack.length, needle.length <= 104
  • haystack 和 needle 仅由小写英文字符组成

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/implement-strstr
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

Analyse

暴力解法是两个for循环,若haystack长度为m,needle长度为n,则算法复杂度为O(m*n)

看到这个题很容易想到要用KMP,算法复杂度为O(m + n),生成next数组O(n),遍历haystack O(m)

计算next数组

next数组有不同的版本,这也是我学KMP遇到的问题之一,我选用的版本是PMT右移一个下标,然后next[0]设置为-1
计算next数组时只需要needle字符串

needle:abababca

char a b a b a b c a
index 0 1 2 3 4 5 6 7
PMT 0 0 1 2 3 4 0 1
next -1 0 0 1 2 3 4 0

部分匹配表(Partial Match Table),填入 前缀和后缀(不包括整个字符串)相等的最大长度

aba,前缀{a, ab},后缀{ba, a},相等的前缀和后缀最大长度为1 (a)
abab,前缀{a, ab},后缀{ab, b},最大长度为2 (ab)
ababa,最长的相等前后缀为aba,长度为3

class Solution {
    public int strStr(String haystack, String needle) {
        // kmp

        // 计算next数组
        int[] next = calcNext(needle);

        // 开始KMP
        int i = 0, j = 0;

        while (i < haystack.length() && j < needle.length()) {
            if (j == -1 || haystack.charAt(i) == needle.charAt(j)) {
                i++;
                j++;
            } else {
                j = next[j];
            }
        }

        // j走到尽头标识匹配成功
        if (j == needle.length()) {
            return i - j;
        }

        return -1;
    }

    public int[] calcNext(String needle) {
        int len = needle.length();

        int[] next = new int[len + 1];
        next[0] = -1;

        int i = 0, j = -1;

        // needle和needle匹配,生成next
        while (i < len) {
            if (j == -1 || needle.charAt(i) == needle.charAt(j)) {
                // 如果是因为 j == -1进来的,next[i] 会被赋值为0,表明最大相同前后缀长度为0
                i++;
                j++;
                next[i] = j;
            } else {
                // mismatch时j向前找,一直mismatch的话j会变成-1(next[0]=-1)
                // j = -1代表前缀和后缀没有相同的,最大长度为0
                j = next[j];
            }
        }

        return next;
    }
}

References

  1. 如何更好地理解和掌握 KMP 算法?
  2. https://www.bilibili.com/video/BV1PD4y1o7nd
posted @ 2022-05-19 19:44  arcsinW  阅读(23)  评论(0编辑  收藏  举报