#include <iostream> #include <cstring> #include <cstdio> #include <vector> #include <string> using namespace std; char pat[1111]; int next[1111]; void getNext(int len) { int i = 1, j = 0; next[1] = 0; while (i < len) { if (j == 0 || pat[i] == pat[j]) { ++i, ++j; next[i] = j; } else j = next[j]; } for (int i = 1; i <= len; i++) cout << next[i] << " "; cout << endl; } void getnextval(int len) { int i = 1, j = 0; next[1] = 0; while (i < len) { if (j == 0 || pat[i] == pat[j]) { ++i, ++j; if (pat[i] != pat[j])next[i] = j; else next[i] = next[j]; } else j = next[j]; } for (int i = 1; i <= len; i++) cout << next[i] << " "; cout << endl; } int main() { while (scanf("%s", pat + 1)) { int len = strlen(pat + 1); getNext(len); getnextval(len); } }
一直对于这两种next弄得不是很清楚,仔细看了几篇博客后发现是这么回事: 比如s="ababab", 当s[6]失配的时候可以移动到4,当然也可以移动到1。 在做匹配的话移动到1是效率高点的,因为这样有效移动距离最远,少了一次移位,当然这种不是最优的next数组还是有用的,比如
[POJ2752]Seek the Name, Seek the Fame,这题如果用优化的KMP的就得不到想要的答案,这题要的就是所有的对称串,用优化的KMP得不到所有的答案。 另外一种就是直接移位到最优点,效率高些。就如上面那个s="ababab"的例子,next[6]直接就移到1,而不是移到4。 严蔚敏版代码:
转载于:https://www.cnblogs.com/ofpsxx/p/3592423.html