hdu 3746(kmp)

 1 /*

 2 *  kmp

 3 */

 4 

 5 #include <cstdio>

 6 #include <cstring>

 7 #include <iostream>

 8 

 9 using namespace std;

10 

11 const int N = 100005;

12 

13 int next[N];

14 char pat[N];

15 

16 void indexNext() {

17     int k = 0;

18     next[1] = 0;

19     for (int i=2; pat[i]; ++i) {

20         while (k && pat[k+1]!=pat[i]) k = next[k];

21         if (pat[k+1] == pat[i]) ++k;

22         next[i] = k;

23     }

24 }

25 

26 int solve() {

27     indexNext();

28     int len = strlen(pat);

29     if ((len-1)%(len-next[len-1]-1)==0) {//串是周期的 

30         if (next[len-1]) return 0;//周期数大于1 

31         else return len - 1;//周期数等于1 

32     }

33     else return (len-next[len-1]-1)-(len-1)%(len-next[len-1]-1);//串是非周期的,最短周期长度减去不完整周期的长度 

34 }

35 

36 int main() {

37     int t;

38     scanf ("%d", &t);

39     pat[0] = '#';

40     while (t--) {

41         scanf ("%s", pat+1);

42         printf ("%d\n", solve());

43     }

44     return 0;

45 }

 

你可能感兴趣的:(HDU)