Skip to content

Instantly share code, notes, and snippets.

@manuchandel
Created August 25, 2015 16:46
Show Gist options
  • Save manuchandel/7c540b7f39746077070b to your computer and use it in GitHub Desktop.
Save manuchandel/7c540b7f39746077070b to your computer and use it in GitHub Desktop.
int KMP(string T,string p){
int n=p.length();
int N=T.length();
int *A=new int[n];
longestPrefixSuffix(p,A,n); // compute lps array
int i=0,j=0;
while(i<N){
if(j==n){ // pattern found
delete []A;
return i-n;
}
if(T[i]==p[j]){
i++;
j++;
}else if(j==0) i++;
else j=A[j-1];
}
delete []A; // delete A to avoid memory leak
if(j==n)
return i-n;
return -1; // if not found return -1
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment