Reputation: 196
I would require to find a repeated pattern if it exists in a string or return a string in case repeated pattern does not exists.
Example:
String s = "abcabc"; Repeated pattern is abc
String s = "aba"; Repeated pattern is aba
String s = "abbbbbbba"; Repeated pattern is abbbbbbba;
String s ="abcdabcdabcd"; Repeated pattern is abcd;
If you refer to link we can solve this using regex Finding a repeated pattern in a string . But apart from regex is there some other way in which I can get it solved?
Upvotes: 0
Views: 1087
Reputation: 894
If there is a pattern => its length must divide the string length
for (int i =2;i < sqrt(length(s));i++)
{
if(length(s) % i == 0)
{
string pattern = s.substring(0,i);
bool isPatern = true;
int j = i +1;
while(isPatern && j<length(s))
{
if(s.substring(j,i)==pattern)
{
j = j+i;
}
else
{
isPatern =false;
}
}
if (isPattern) return pattern;
}
}
Note that this will return the smallest pattern, if you want the longest you do a for (int i =length(s)/2;i > sqrt(length(s));i--)
Upvotes: 1