Puzzle:
For two strings A and B, we define the similarity of the strings to be the length of the longest prefix common to both strings. For example, the similarity of strings "abc" and "abd" is 2, while the similarity of strings "aaa" and "aaab" is 3. Calculate the sum of similarities of a string S with each of its suffixes.
Explanation:
For ababaa the suffixes of the string are "ababaa", "babaa", "abaa", "baa", "aa" and "a". The similarities of each of these strings with the string "ababaa" are 6,0,3,0,1,1 respectively. Thus the answer is 6 + 0 + 3 + 0 + 1 + 1 = 11.
How can I improve execution time of this (when larger testcases are provided)?
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
Scanner scanner;
Solution sr = new Solution();
scanner = new Scanner(System.in);
int no_cases = scanner.nextInt();
for (int i = no_cases; --i >=0; ) {
String to_proc = scanner.next();
sr.solve(to_proc);
}
}
private void solve(String to_proc) {
String str=to_proc;
int len=to_proc.length();
int count=0;
int total=0;
for(int i=1;i<len;i++)
{
count=0;
for(int j=i;j<len;j++)
{
// System.out.println(str.charAt(j)+" , "+str.charAt(j-i));
if(str.charAt(j-i)==str.charAt(j))
{
count++;
}
else
{
break;
}
}
total=total+count;
}
System.out.println(total+len);
}
}