1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
| #include<stdio.h> #include<stdlib.h> #include<iostream> #include<string.h>
using namespace std;
int* nextArray(const char* pattern, int m) { int* next = new int[m]; next[0] = -1; int j = 0; int k = -1; while (j < m - 1) { if (k == -1 || pattern[j] == pattern[k]) { j++; k++; next[j] = k; } else { k = next[k]; } } return next; }
int* nextValueArray(const char* pattern, int m) { int* nextVal = new int[m]; nextVal[0] = -1; int j = 0; int k = -1; while (j < m - 1) { if (k == -1 || pattern[j] == pattern[k]) { j++; k++; if (pattern[j] != pattern[k]) { nextVal[j] = k; } else { nextVal[j] = nextVal[k]; } } else { k = nextVal[k]; } } return nextVal; }
int KMP(const char* text, const char* pattern) { int n = strlen(text); int m = strlen(pattern); int* next = nextArray(pattern, m); int i = 0; int j = 0; while (i < n && j < m) { if (j == -1 || text[i] == pattern[j]) { i++; j++; } else { j = next[j]; } } delete[] next; if (j == m) { return i - j; } else { return -1; } }
int main() { const char* text = "ababcabcacbab"; const char* pattern = "abcac"; int position = KMP(text, pattern); if (position != -1) { cout << "Pattern found at index: " << position << endl; } else { cout << "Pattern not found." << endl; } return 0; }
|