459. Repeated Substring Pattern

题目链接:https://leetcode.com/problems...

利用kmp求prefix数组的方法来做,利用string自身的重复性,prefix[i] = k, k < i表示在s[0, i+1]中,最大的k使得s[0, k] == s[i-k+1, i+1]
参考视频:
https://www.youtube.com/watch...

所以如果这个string是呈现repeated substring pattern的样子的话,假设repeat的大小是m,则prefix[0] = prefix[1] = ... = prefix[m-1] = 0 并且prefix[n-1] = prefix[n-2] + 1 =... = prefix[m] + n-m-1 = n - m
根据n % m == 0可知:n%(n - prefix[n-1]) == 0,一旦中间出现不满足pattern的情况,prefix[n-1] < n / 2,所以n-prefix[n-1] > n / 2必然不是n的divisor,如果结尾处少了的话,例如abcabca,虽然prefix[n-1] > n/2,但不满足divisor的条件。

public class Solution {
    public boolean repeatedSubstringPattern(String str) {
        int[] prefix = build(str);
        int n = str.length();
        return prefix[n-1] != 0 && n % (n - prefix[n-1]) == 0;
    }
    
    private int[] build(String s) {
        int n = s.length();
        int[] res = new int[n];
        int i = 1, j = 0;
        while(i < n) {
            // match, add the length
            if(s.charAt(i) == s.charAt(j)) {
                res[i] = j + 1;
                i++; j++;
            }
            // not match, return to previous
            else {
                if(j == 0) i++;
                else j = res[j-1];
            }
        }
        return res;
    }
}

lulouch13
13 声望6 粉丝