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

给你两个字符串 haystack 和 needle ,请你在 haystack 字符串中找出 needle 字符串的第一个匹配项的下标(下标从 0 开始)。如果 needle 不是 haystack 的一部分,则返回  -1 。

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/find-the-index-of-the-first-occurrence-in-a-string
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。


KMP

class Solution {

    private int[] getNext(String needle) {
        int[] next = new int[needle.length()];
        next[0] = -1;
        int i = 0, j = -1;
        while (i < needle.length() - 1) {
            if (j == -1 || needle.charAt(i) == needle.charAt(j)) {
                if (needle.charAt(++i) == needle.charAt(++j)) {
                    next[i] = next[j];
                } else {
                    next[i] = j;
                }
            } else {
                j = next[j];
            }
        }
        return next;
    }

    public int strStr(String haystack, String needle) {
        if (haystack == null || haystack.length() == 0) {
            return needle == null || needle.length() == 0 ? 0 : -1;
        }

        if (needle == null || needle.length() == 0) {
            return 0;
        }

        int[] next = getNext(needle);
        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];
            }
        }
        return j == needle.length() ? i - j : -1;
    }
}

Rabin-Karp

class Solution {

    private int BASE = 37;

    private int MOD = 1000000007;

    public int strStr(String haystack, String needle) {
        long high = 1L;
        for (int i = 1; i < needle.length(); i++) {
            high = (high * BASE) % MOD;
        }
        long expect = 0;
        for (int i = 0; i < needle.length(); i++) {
            expect = (expect * BASE + needle.charAt(i)) % MOD;
        }

        int left = 0, right = 0;
        long sum = 0;
        while (right < haystack.length()) {
            sum = ((sum * BASE) + haystack.charAt(right++)) % MOD;
            if (right - left == needle.length()) {
                if (sum == expect) {
                    return left;
                }
                sum = (sum - haystack.charAt(left++) * high % MOD + MOD) % MOD;
            }
        }
        return -1;
    }
}
posted @ 2023-03-21 00:08  Tianyiya  阅读(23)  评论(0)    收藏  举报