Skip to content

Instantly share code, notes, and snippets.

@phaniram
Created December 29, 2011 22:41
Show Gist options
  • Save phaniram/1536524 to your computer and use it in GitHub Desktop.
Save phaniram/1536524 to your computer and use it in GitHub Desktop.
Interview Street Challenges - String similarity
package com.interviewstreet.puzzles;
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 = 0; i < no_cases; i++) {
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);
}
}
@phaniram
Copy link
Author

String Similarity (25 Points)
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 it's suffixes.
Input:
The first line contains the number of test cases T. Each of the next T lines contains a string each.
Output:
Output T lines containing the answer for the corresponding test case.
Constraints:
1 <= T <= 10
The length of each string is at most 100000 and contains only lower case characters.
Sample Input:
2
ababaa
aa
Sample Output:
11
3
Explanation:
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.
For the second case, the answer is 2 + 1 = 3.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment