问题描述:
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.
思路:
首先想到的是最简单的方法。遍历所有可能的子字符串长度,一一比较是否为重复子符串的组合。
代码:
class Solution {
public boolean repeatedSubstringPattern(String s) {
int n = s.length();
for(int i = 1; i <= n / 2; i++){
if(n % i != 0) continue;
String refer = s.substring(0, i);
int a = 1;
for(int j = i; j < n; j = j + i){
String tmp = s.substring(j, j+i);
if(!refer.equals(tmp)){
a = 0;
break;
}
}
if(a == 1) return true;
}
return false;
}
}
网络上很多说利用KMP算法,从头到尾彻底理解KMP,这个链接讲的比较详细,后面理解透彻后再进行整理。