标签:des style io os ar for div sp cti
Description
Input
Output
Sample Input
ababcababababcabab aaaaa
Sample Output
2 4 9 18 1 2 3 4 5 题意:求既匹配字符串前缀又匹配后缀的字符串的长度 思路:其实next[]数组就表示的是最长的前缀和后缀匹配,那么只要next[]数组的值不为0的话,就代表有前后缀匹配,递归下去,当然整个字符串也符合条件#include <iostream> #include <cstdio> #include <cstring> #include <algorithm> using namespace std; const int maxn = 400010; char pattern[maxn]; int next[maxn], flag; void getNext() { int m = strlen(pattern); next[0] = next[1] = 0; for (int i = 1; i < m; i++) { int j = next[i]; while (j && pattern[i] != pattern[j]) j = next[j]; next[i+1] = pattern[i] == pattern[j] ? j+1 : 0; } } void dfs(int len) { if (len == 0) return; dfs(next[len]); if (!flag) { printf("%d", len); flag = 1; } else printf(" %d", len); } int main() { while (scanf("%s", pattern) != EOF) { getNext(); int len = strlen(pattern); flag = 0; dfs(len); printf("\n"); } return 0; }
POJ - 2752 Seek the Name, Seek the Fame (KMP的next[]应用)
标签:des style io os ar for div sp cti
原文地址:http://blog.csdn.net/u011345136/article/details/39249525