[459]repeated substring pattern

repeated substring pattern

This problem can be solved using KMP table by O(n).

kmp by july

idea

if the string has repeated pattern, then it must has a common prefix and suffix. that is the same thing when we implement KMP.

Then we will first calculated the longest common-fix table.

Then we can judge by:

common != 0 && len % (len - common) == 0;

code

public class Solution{

    public boolean repeatedSubstringPattern(String str) {
        int len = str.length();
        if(len == 0)return true;
        int[] table = presuf(str);
        int common = table[len - 1];
        return common != 0 && len % (len - common) == 0;
    }
    public int[] presuf(String s){

        int len = s.length();

        int[] table = new int[len];
        if(len == 0)return table;


        for(int i = 1; i < len; i++){
            int last = table[i - 1];
            while(true){

                if(s.charAt(i) == s.charAt(last)){
                    table[i] = last + 1;
                    break;
                } else {
                    if(last == 0)break;
                    last = table[last - 1];

                }
            }

        }
        return table;

    }

}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • **2014真題Directions:Read the following text. Choose the be...
    又是夜半驚坐起閱讀 11,097評論 0 23
  • 三天的假期很快就要結(jié)束了。 三天,無所事事。 上網(wǎng)上到天快亮; 睡覺睡到自然醒。 零食、書、衣服亂丟,故意讓房間凌...
    高小花0218閱讀 335評論 0 1
  • 地方與家,面孔與親人,南方南方,最后終于去了南方 音樂與酒,歡樂與舊人,家駒家駒,靈魂里遇到的家駒 一年四季未如愿...
    沉阿姣閱讀 206評論 0 1
  • 我想沉睡 可是你和喜歡 擾人清夢
    布谷娘閱讀 276評論 0 0

友情鏈接更多精彩內(nèi)容