Created
August 25, 2015 16:46
-
-
Save manuchandel/7c540b7f39746077070b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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