Swapneel
Swapneel

Reputation: 196

Method to find Repeated pattern in String apart from Regex

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:

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

Answers (1)

AnotherGeek
AnotherGeek

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

Related Questions