LeetCode 459. Repeated Substring Pattern

原題網址:https://leetcode.com/problems/repeated-substring-pattern/

Given a non-empty string check if it can be constructed by taking a substring of it and appending multiple copies of the substring together. You may assume the given string consists of lowercase English letters only and its length will not exceed 10000.

Example 1:

Input: "abab"

Output: True

Explanation: It's the substring "ab" twice.

Example 2:

Input: "aba"

Output: False

Example 3:

Input: "abcabcabcabc"

Output: True

Explanation: It's the substring "abc" four times. (And the substring "abcabc" twice.)

方法:只需要檢查切分爲素數個。

public class Solution {
    public boolean repeatedSubstringPattern(String str) {
        char[] sa = str.toCharArray();
        boolean[] checked = new boolean[sa.length + 1];
        for(int i = 2; i <= sa.length; i++) {
            if (sa.length % i != 0) continue;
            if (checked[i]) continue;
            for(int j = i; j <= sa.length; j += i) {
                checked[j] = true;
            }
            boolean succ = true;
            ALL: for(int j = 0; j < i - 1; j++) {
                for(int k = 0; k < sa.length / i; k++) {
                    if (sa[j * sa.length / i + k] != sa[(j + 1) * sa.length / i + k]) {
                        succ = false;
                        break ALL;
                    }
                }
            }
            if (succ) return true;
        }
        return false;
    }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章