| 2 | using namespace std; |
| 3 | |
| 4 | void computeLPSArray(string pat, int M, int *lps) |
| 5 | { |
| 6 | // length of the previous longest prefix suffix |
| 7 | int len = 0; |
| 8 | |
| 9 | lps[0] = 0; // lps[0] is always 0 |
| 10 | |
| 11 | // the loop calculates lps[i] for i = 1 to M-1 |
| 12 | int i = 1; |
| 13 | while (i < M) |
| 14 | { |
| 15 | if (pat[i] == pat[len]) |
| 16 | { |
| 17 | len++; |
| 18 | lps[i] = len; |
| 19 | i++; |
| 20 | } |
| 21 | else // (pat[i] != pat[len]) |
| 22 | { |
| 23 | // This is tricky. Consider the example. |
| 24 | // AAACAAAA and i = 7. The idea is similar |
| 25 | // to search step. |
| 26 | if (len != 0) |
| 27 | { |
| 28 | len = lps[len - 1]; |
| 29 | |
| 30 | // Also, note that we do not increment |
| 31 | // i here |
| 32 | } |
| 33 | else // if (len == 0) |
| 34 | { |
| 35 | lps[i] = 0; |
| 36 | i++; |
| 37 | } |
| 38 | } |
| 39 | } |
| 40 | } |
| 41 | // Prints occurrences of txt[] in pat[] |
| 42 | void KMPSearch(string pat, string txt) |
| 43 | { |