1. 程式人生 > 其它 >686. 重複疊加字串匹配

686. 重複疊加字串匹配

給定兩個字串a 和 b,尋找重複疊加字串 a 的最小次數,使得字串 b 成為疊加後的字串 a 的子串,如果不存在則返回 -1。

注意:字串 "abc"重複疊加 0 次是 "",重複疊加 1 次是"abc",重複疊加 2 次是"abcabc"。

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

KMP

class Solution {

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

    public int repeatedStringMatch(String a, String b) {
        int[] next = getNext(b);
        int i = 0, j = 0;
        while (i - j < a.length() && j < b.length()) {
            if (j == -1 || a.charAt(i % a.length()) == b.charAt(j)) {
                i++;
                j++;
            } else {
                j = next[j];
            }
        }
        if (j != b.length()) {
            return -1;
        }
        return i % a.length() == 0 ? i / a.length() : i / a.length() + 1;
    }
}

Rabin-Karp

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