Last active
February 18, 2017 20:05
-
-
Save CsengerG/f03b129d7df7fc700f9b291fc3c95391 to your computer and use it in GitHub Desktop.
Knuth-Morris-Pratt: search for a pattern
This file contains hidden or 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
| void kmp(){ | |
| int q = 0; // the position in P | |
| int i = 0; // the position in T | |
| while( i < n ){ // go through the entire array | |
| if( P[q+1] == T[i+1] ){ // if a match continues, we increase the positions | |
| q++; | |
| i++; | |
| if( q == m ){ // if q reached m, it means that we have a match | |
| cout << "match from " << i-m+1 << endl; | |
| q = pi[q]; // but we want to find all the matches, so we continue | |
| } | |
| } else { // a mismatch occured | |
| if(q==0) ++i; // if q=0, we just continue in T | |
| else q = pi[q]; // else, we have to jump according the precomputed array | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment