int kmp(const string &str, const string &pattern) { vector<int> next(pattern.size()); makeNext(pattern, next); int k = 0; for(int i = 0; i < str.size(); ++i) { while(k > 0 && str[i] != pattern[k]) k = next[k - 1]; if(str[i] == pattern[k]) ++k; if(k == pattern.size()) return i - k + 1; } return -1; }
int kmp(const char T[], const char P[], int next[]) { int n, m; int i, q; n = strlen(T); m = strlen(P); makeNext(P, next); for (i = 0, q = 0; i < n; ++i) { while (q > 0 && P[q] != T[i]) q = next[q - 1]; if (P[q] == T[i]) { q++; } if (q == m) { printf("Pattern occurs with shift:%d\n", (i - m + 1)); // q=0; } } }
int kmp(const char* s, const char* pattern, int* matches) { int len = strlen(s); int pattern_len = strlen(pattern); int* next = new int[pattern_len]; makeNext(pattern, next); int n = 0, i = 0, j = 0; while(pattern_len - j < len - i) { while (j>0 && s[i] != pattern[j]) j = next[j-1]; if (s[i] == pattern[j]) j++; if (j == pattern_len) { matches[n++] = i - pattern_len + 1; j = next[j-1]; } i++; } return n; }
int main() { char p[20]; char t[50]; printf("input target:\n"); gets(t); printf("input pattern:\n"); gets(p); int *next = (char*)malloc(strlen(p)*sizeof(int)); makeNext(p, next); printf("the 'next' arg:"); for (int i = 0;i < strlen(p);i++) { printf("%d ", next[i]); } printf("\n"); kmp_match(t, p, next); system("pause"); return 0; }
int kmp(const char T[], const char P[]) { int n = strlen(T); int m = strlen(P); int *next = malloc(n*sizeof(int)); int i, j; makeNext(P, next); for (i = 0, j = 0; i < n; ++i) { while(j > 0 && P[j] != T[i]) j = next[j-1]; if (P[j] == T[i]) j++; if (j == m) { free(next); return i - m + 1; } } free(next); return -1; }