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);
    }
}

你可能感兴趣的:(Repeated Substring Pattern)