1. 程式人生 > 其它 >74HC595數碼管驅動開發

74HC595數碼管驅動開發

給你兩個字串haystack 和 needle ,請你在 haystack 字串中找出 needle 字串出現的第一個位置(下標從 0 開始)。如果不存在,則返回 -1 。

來源:力扣(LeetCode)
連結:https://leetcode-cn.com/problems/implement-strstr
著作權歸領釦網路所有。商業轉載請聯絡官方授權,非商業轉載請註明出處。

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

心之所向,素履以往 生如逆旅,一葦以航