It's a string problem I have been making on Hackerrank. It is executing fine on all test cases except the last two. These last two test case are declaring it "Terminated due to time out".
C programs are allowed 2 seconds on this site and somehow my program is taking a fraction beyond 2 seconds. How am I supposed to reduce that time taken?
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.
#include<stdio.h>
#include<string.h>
void stringMatch(char strMain[]) {
int similarity = 0,i,j;
for(i =0;i<strlen(strMain);i++){
for(j =0;j+i<strlen(strMain);j++){
if(strMain[j] == strMain[j+i]){
similarity++;
}else{
break;
}
}
}
printf("%d\n",similarity);
}
int main(){
int T,i;
scanf("%d",&T);
char str[1000000];
for(i =0;i<T;i++){
scanf("%s",str);
stringMatch(str);
}
}