I am having difficulty finding better approach than O(n^2) for the following question.
I am given a string e.g xyxxz
.
Now I need to find total number of matching characters in each prefix of the given string.
Here, possible prefixes of string are:
xyxxz : matching characters is 5
yxxz : matching characters is 0 (since 1st character doesnt match)
xxz : matching characters is 1
xz : matching characters is 1
z : matching characters is 0
This should be the output. I did the following code:
cin>>str;
len=str.length();
for(i=0;i<len;i++){
sum=0;
k=i;
for(int j=0;j<len;j++)
{
if(str[k] == str[j]){
sum++;
k++;
}
else
break;
}
cout<<sum<<" "; //I get the output 5 0 1 1 0
}
But it's O(n^2). I want a better approach : probably O(n) or O(nlogn).
Thanks in advance.