I implemented KMP which is the solution as in the question but it is giving Time Limit Exceeded.Could someone take a look ?
http://www.spoj.com/problems/NHAY/
void checkForPattern(string haystack,string needle,int *a){
int size=needle.size();
int i=0;
int j=0;
int start=0;
while(j<haystack.size()){
if(needle[i]==haystack[j]){
i++;
j++;
if(i==size){
cout<<j-i<<endl;
start=a[i-1];
i=start;
}
}
else if(a[i]==0){
j++;
i=0;
}
else {
start=a[i]; //check later if it's i-1
i=start;
}
}
}
int *computeFailureFunction(string needle){
int size=needle.size();
int *a=new int[size];
for(int i=0;i<size;i++)
a[i]=0;
int j=0,i=1;
while(i<size){
if(needle[j]==needle[i]){
a[i]=j+1;
j++;
i++;
}
else if(j==0){
a[i]=0;
i++;
}
else
{
j=a[j-1];
}
}
return a;
}
int main(){
int l;
while(cin>>l){
string needle;
string haystack;
cin>>needle>>haystack;
int *a=computeFailureFunction(needle);
checkForPattern(haystack,needle,a);
cout<<endl;
}
return 0;
}