| 31 | } |
| 32 | |
| 33 | void KMP(string txt, string pat) |
| 34 | { |
| 35 | int n = txt.length(); |
| 36 | int m = pat.length(); |
| 37 | int lps[m]; |
| 38 | fillLPS(pat, lps); |
| 39 | |
| 40 | int i = 0, j = 0; |
| 41 | while (i < n) |
| 42 | { |
| 43 | if (txt[i] == pat[j]) |
| 44 | { |
| 45 | i++; |
| 46 | j++; |
| 47 | } |
| 48 | if (j == m) |
| 49 | { |
| 50 | cout << (i - m) << " "; |
| 51 | j = lps[j - 1]; |
| 52 | } |
| 53 | else if (i < n && txt[i] != pat[j]) |
| 54 | { |
| 55 | if (j == 0) |
| 56 | i++; |
| 57 | else |
| 58 | j = lps[j - 1]; |
| 59 | } |
| 60 | } |
| 61 | } |
| 62 | |
| 63 | int main() |
| 64 | { |