title: interviewstreet.com - String similarity
body: <p>I'm trying to solve the string similarity question on interviewstreet.com. My code is working for 7/10 cases (and it is exceeding the time limit for the other 3).</p>
  
  <p>Here's my code - </p>
  
  <pre><code>public class Solution {
  
      public static void main(String[] args) {
  
          Scanner user_input = new Scanner(System.in);
  
          String v1 = user_input.next();
          int number_cases = Integer.parseInt(v1);
  
          String[] cases = new String[number_cases];
          for(int i=0;i&lt;number_cases;i++)
              cases[i] = user_input.next();
  
          for(int k=0;k&lt;number_cases;k++){
              int similarity = solve(cases[k]);   
              System.out.println(similarity);
          }
      }
  
      static int solve(String sample){
  
          int len=sample.length();
          int sim=0;
          for(int i=0;i&lt;len;i++){
              for(int j=i;j&lt;len;j++){
                  if(sample.charAt(j-i)==sample.charAt(j))
                      sim++;
                  else
                      break;
              }
          }
          return sim;
      }
  }
  </code></pre>
  
  <p>Here's the question -</p>
  
  <p>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.</p>
  
  <p>Calculate the sum of similarities of a string S with each of it's suffixes.</p>
  
  <p><strong>Input:</strong><br/>
  The first line contains the number of test cases T. Each of the next T lines contains a string each.</p>
  
  <p><strong>Output:</strong><br/>
  Output T lines containing the answer for the corresponding test case.</p>
  
  <p><strong>Constraints:</strong><br/>
  1 &lt;= T &lt;= 10<br/>
  The length of each string is at most 100000 and contains only lower case characters.</p>
  
  <p><strong>Sample Input:</strong><br/>
  2<br/>
  ababaa<br/>
  aa</p>
  
  <p><strong>Sample Output:</strong><br/>
  11<br/>
  3</p>
  
  <p><strong>Explanation:</strong><br/>
  For the first case, 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.</p>
  
  <p>For the second case, the answer is 2 + 1 = 3.</p>
  
  <p>How can I improve the running speed of the code. It becomes harder since the website does not provide a list of test cases it uses.</p>