# Repeated-Substring-Pattern

Jan 22, 2018

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.)

bool repeatedSubstringPattern1(string s) {
for(int i = 1;i < s.size();i++)
if (repeatedSubstringPattern(s,i)) return true;
return false;
}
bool repeatedSubstringPattern(string &s,int p) {
// cout << p << endl;
int size = s.size();
if (size % p) return false;
for(int i = 0;i < p;i++) {
for(int j = i+p;j < size;j += p) {
//cout << s[i] << " " << s[j] << endl;
if (s[i] != s[j]) return false;
}
}
return true;
}


bool repeatedSubstringPattern(string str) {
int i = 1, j = 0, n = str.size();
vector<int> dp(n+1,0);
while( i < str.size() ){
if( str[i] == str[j] ) dp[++i]=++j;
else if( j == 0 ) i++;
else j = dp[j];
}
return dp[n]&&dp[n]%(n-dp[n])==0;
}

LeetCodeLeetCode

Rotate-Image