类比POJ 2406
1 #include <cstdio> 2 #include <cstring> 3 #include <iostream> 4 using namespace std; 5 typedef long long LL; 6 7 const int maxn = 1e6 + 10; 8 int next[maxn]; 9 10 void kmp(char *pattern) { 11 //int n = pattern.size(); 12 int n = strlen(pattern); 13 for (int i = 1; i < n; i++) { 14 int j = i; 15 while (j > 0) { 16 j = next[j]; 17 if (pattern[j] == pattern[i]) { 18 next[i + 1] = j + 1; 19 break; 20 } 21 } 22 } 23 } 24 25 26 int main() { 27 char s[maxn]; 28 while (~scanf("%s", s)) { 29 memset(next, 0, sizeof(next)); 30 kmp(s); 31 int len = strlen(s); 32 printf("%d\n", len - next[len]); 33 } 34 return 0; 35 }
时间: 2024-10-07 01:22:03