题目链接
实现 strStr() 函数。
给你两个字符串 haystack 和 needle ,请你在 haystack 字符串中找出 needle 字符串出现的第一个位置(下标从 0 开始)。如果不存在,则返回 -1 。

说明:
当 needle 是空字符串时,我们应当返回什么值呢?这是一个在面试中很好的问题。
对于本题而言,当 needle 是空字符串时我们应当返回 0 。这与 C 语言的 strstr() 以及 Java 的 indexOf() 定义相符。

示例 1:

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

示例 2:

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

提示:

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

思路

遍历

class Solution {
    public int strStr(String haystack, String needle) {
        if (needle == null) {
            return 0;
        }
        for (int i = 0; i < haystack.length() - needle.length() + 1; i++) {
            boolean flag = true;
            for (int j = 0; j < needle.length(); j++) {
                if (haystack.charAt(i + j) != needle.charAt(j)) {
                    flag = false;
                    break;
                }
            }
            if (flag == true) {
                return i;
            }
        }
        return -1;
    }
}

KMP

kmp算法思路

class Solution {
    // 以最长相等前后缀长度为前缀表
    public int strStr(String haystack, String needle) {
        // 当模式串needle长度为0时,返回0
        if (needle.length() == 0) {
            return 0;
        }
        // 创建next数组
        int[] next = new int[needle.length()];
        // 求next数组
        getNext(next, needle);

        // 使用next数组求needle字符串在haystack中出现的第一个位置
        int j = 0; // 模式串needle的下标
        // i是文本串haystack的下标
        for (int i = 0; i < haystack.length(); i++) {
            // 当j > 0且j指向的needle的字符与i指向的haystack的字符不相同时
            // j开始回退,回退到j前一位的next数组值的位置,如果仍不相等,继续回退
            while (j > 0 && needle.charAt(j) != haystack.charAt(i)) {
                j = next[j - 1];
            }
            // 如果j指向的needle的字符与i指向的haystack的字符相同时,继续匹配下一位,j++同时for循环会让i++
            // (除了下面判断的匹配结束的情况)
            if (needle.charAt(j) == haystack.charAt(i)) {
                j++;
            }
            // 当j等于needle的长度时,说明整个needle已经与haystack中某一段匹配上了,return结果
            if (j == needle.length()) {
                return i - needle.length() + 1;
            }
        }
        return -1;
    }

    // 求next数组
    private void getNext(int[] next, String needle) {
        // 1. 初始化
        int j = 0; // j是前缀的末尾(也是i包括i以前的最长相等前后缀的长度)
        next[0] = 0; // 只有一个字符的情况,没有前缀也没有后缀,前缀表数值为0
        // i是后缀末尾的位置
        for (int i = 1; i < needle.length(); i++) {
            // 2. 处理i和j字符不同的情况
            // 找到前一位的next数组数组值,回退,继续匹配
            while (j > 0 && needle.charAt(i) != needle.charAt(j)) {
                j = next[j - 1];
            }
            // 3. 处理i和j字符相同的情况
            // j后移一位
            if (needle.charAt(j) == needle.charAt(i)) {
                j++;
            }
            // 更新next数组
            next[i] = j;
        }
    }
}