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.

答案

一个非常直观的写法(也很快[why??],beat 96%)

class Solution {
    public boolean repeatedSubstringPattern(String s) {
        int n = s.length();
        if(n < 2) return false;
        for(int i = 1; i <= n / 2; i++) {
            if(n % i == 0) {
                // Is s.substr(0, i) repeated across the string ?
                String cmp = s.substring(0, i);
                int j = i;
                while(j < n) {
                    if(s.startsWith(cmp, j) == false) break;
                    j += i;
                }
                if(j == n) return true;
            }
        }
        return false;
    }
}

一个很neat的算法(有点慢)

class Solution {
    public boolean repeatedSubstringPattern(String s) {
        String s2 = s + s;
        return new String(s2).substring(1, s2.length() - 1).contains(s);
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容