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
Here is my solution...
#include<stdio.h>
#include<string.h>
int getSim(char str[],int subindex)
{
int l2=subindex
int i=0;
int count=0;
for(i=0;i<l2;i++)
if(str[i]==str[subindex])
{
count++;
subindex++;
}
else
break;
return count;
}
int main()
{
int testcase=0;
int len=0;
int sum=0;
int i=0;
char s[100000];
scanf("%d",&testcase);
while(testcase--)
{
sum=0;
scanf("%s",s);
for(i=0;i<strlen(s);i++)
if(s[i]==s[0])
{
sum=sum+getSim(s,i);
}
printf("%d\n",sum);
}
}
How can we go about solving this problem using suffix array??
You mention in the comments that it is correct, but it's very slow.
In Java, you can get the length of a
String
withs.length()
- this value is cached in the object and it isO(1)
to get.But when you go to C, you get the length of a string with
strlen(s)
which recalculates (inO(n)
) each time. So while you should be doingO(n)
, because you have anO(n)
operation in there, the entire function becomesO(n^2)
.To get around this, cache the value once when you run it. This will bring you back into linear time.
Bad:
Good: