Not really sure if this is purely a maths question.. I am looking if there is a faster way to look for cyclic repetitions in an input string. Say for example the input string is abcabcdabcabcd, it has 2 repetitions of abcabcd.
public class CyclicSimilarity {
public static void main(String[] args)
{
String S =
("abcabcdabcabcd");
int x = S.length();
boolean foundAns = false;
ArrayList<Integer> fact = new ArrayList<Integer>();
for(int i=1; i<=x; i++)
{
if(x%i == 0)
fact.add(i);
}
System.out.println("Factors are : "+fact.toString());
for(int i=0; i<fact.size()-1; i++)
{
if(match(fact.get(i), 0, S))
{
System.out.println("Answer : "+S.length()/fact.get(i));
foundAns = true;
break;
}
}
if(!foundAns)
System.out.println("Answer : 1");
}
private static boolean match(Integer f, int i, String S) {
boolean boolRet = false;
if(S.substring(i, i+f).equalsIgnoreCase(S.substring(i+f, i+f+f)))
{
if(i+f+f == S.length())
return true;
boolRet = match(f,i+f,S);
return boolRet;
}
else
return false;
}
}