本文共 766 字,大约阅读时间需要 2 分钟。
- #include <iostream>
- #include <cstdlib>
- #include <cstdio>
- using namespace std;
-
- int get_next(const char*t, int *next)
- {
- int i = 0;
- int j = -1;
- int len = strlen(t);
- memset(next,0, sizeof(int) * len);
- next[0] = -1;
- while(i < len - 1)
- {
- if(j == -1 || t[i] == t[j])
- {
- i++;
- j++;
- next[i] = j;
- }
- else
- j = next[j];
- }
- }
-
- int kmp(const char *s, const char *t)
- {
- int i = 0;
- int j = 0;
- int next[100];
- get_next(t,next);
- while(i < strlen(s) && j < strlen(t))
- {
- if(j == - 1 || s[i] == t[j])
- {
- i++;
- j++;
- }
- else
- j = next[j];
- }
-
- if(j >= (int)strlen(t))
- {
- cout << "found " << endl;
- return 0;
- }
-
- cout << "not found" <<endl;
- return 0;
- }
转载于:https://www.cnblogs.com/luzhongshan/p/3868376.html