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);    }}
Calculating sum of similarities of strings
java;optimization;performance;strings;programming challenge
Converting the input String to char[] helps a little bit but I cannot profile it now.private void solve2(final String input) {    int total = 0;    final char[] inputArray = input.toCharArray();    for (int i = 1; i < inputArray.length; i++) {        int count = 0;        for (int j = i; j < inputArray.length; j++) {            if (inputArray[j - i] != inputArray[j]) {                break;            }            count++;        }        total = total + count;    }    System.out.println(total + inputArray.length);}String.charAt does some index checks, so I suppose the cause of the performance improvement is the missing checks.public char charAt(int index) {    if ((index < 0) || (index >= count)) {        throw new StringIndexOutOfBoundsException(index);    }    return value[index + offset];}Anyway, profile the code. Modern IDEs usually have profiler.Another idea is using multiple threads.