PROBLEM:
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.
Example 1:
Input: "abab" Output: True Explanation: It's the substring "ab" twice.
Example 2:
Input: "aba" Output: False
Example 3:
Input: "abcabcabcabc" Output: True Explanation: It's the substring "abc" four times. (And the substring "abcabc" twice.)
SOLVE:
bool repeatedSubstringPattern(string str) {
int i = 1, j = 0, n = str.size();
vector<int> dp(n+1,0);
dp[0]=-1;
while( i < str.size() ){
if( j==-1||str[i] == str[j] )
dp[++i]=++j;
else
j = dp[j];
}
return dp[n]&&dp[n]%(n-dp[n])==0;
}
分析(KMP算法):这种方法用到了KMP算法,其中dp[i]中的i从0开始,dp[i]的值为“当前字符str[i]与模式字符str[j]不相同时,j跳至的下标”,其实也表示“当前字符之前,前缀与后缀相同的最大长度”,如str=“abcdabcd”,则str[5]=’b’,’b’之前的子字符串“abcda”前缀a与后缀a相同,相同的最长长度为1,所以dp[5]=1。str[1]之前只有一个字符,所以dp[1]=0,由于当j==0&&str[i] != str[j]时,j=dp[j]=-1,下一次循环dp[i+1]=j+1=0,再次循环进行str[0]和str[i+1]的比较…
public boolean repeatedSubstringPattern(String str) {
int l = str.length();
for(int i=l/2;i>=1;i--) {
if(l%i==0) {
int m = l/i;
String subS = str.substring(0,i);
StringBuilder sb = new StringBuilder();
for(int j=0;j<m;j++) {
sb.append(subS);
}
if(sb.toString().equals(str)) return true;
}
}
return false;
}
分析:此方法主要利用“字符串重复,则输入字符串长度必然为模式字符串长度的整数倍”的性质,比较好理解。