[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;

    }

}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 9,998评论 0 23
  • 三天的假期很快就要结束了。 三天,无所事事。 上网上到天快亮; 睡觉睡到自然醒。 零食、书、衣服乱丢,故意让房间凌...
    高小花0218阅读 321评论 0 1
  • 地方与家,面孔与亲人,南方南方,最后终于去了南方 音乐与酒,欢乐与旧人,家驹家驹,灵魂里遇到的家驹 一年四季未如愿...
    沉阿姣阅读 179评论 0 1
  • 我想沉睡 可是你和喜欢 扰人清梦
    布谷娘阅读 243评论 0 0