24h購物| | PChome| 登入
2012-02-22 07:06:46| 人氣3,609| 回應0 | 上一篇 | 下一篇

[UVA] 455 - Periodic Strings

推薦 0 收藏 0 轉貼0 訂閱站台

 Periodic Strings 

A character string is said to have period k if it can be formed by concatenating one or more repetitions of another string of length k. For example, the string "abcabcabcabc" has period 3, since it is formed by 4 repetitions of the string "abc". It also has periods 6 (two repetitions of "abcabc") and 12 (one repetition of "abcabcabcabc").

Write a program to read a character string and determine its smallest period.

Input

The first line oif the input file will contain a single integer N indicating how many test case that your program will test followed by a blank line. Each test case will contain a single character string of up to 80 non-blank characters. Two consecutive input will separated by a blank line.

Output

An integer denoting the smallest period of the input string for each input. Two consecutive output are separated by a blank line.

Sample Input

1

HoHoHo

Sample Output

2



做法 : KMP

#include<stdio.h>
#include<string.h>
#define MaxL 1000
int KMP_init(char *A) {
int i, j;
int P[MaxL];
P[0] = -1, i = 1, j = -1;
while(A[i]) {
while(j >= 0 && A[j+1] != A[i])
j = P[j];
if(A[j+1] == A[i])
++j;
P[i] = j, ++i;
}
return j;
}
int main() {
int T;
char s[MaxL];
scanf("%d", &T);
while(T--) {
scanf("%s", s);
int l = strlen(s), t = KMP_init(s);
if(l%(l-t-1))
printf("%d\n", l);
else
printf("%d\n", l-t-1);
if(T) puts("");
}
return 0;
}

台長: Morris
人氣(3,609) | 回應(0)| 推薦 (0)| 收藏 (0)| 轉寄
全站分類: 不分類 | 個人分類: UVA |
此分類下一篇:[UVA] 10298 - Power Strings
此分類上一篇:[UVA] 10020 - Minimal coverage

是 (若未登入"個人新聞台帳號"則看不到回覆唷!)
* 請輸入識別碼:
請輸入圖片中算式的結果(可能為0) 
(有*為必填)
TOP
詳全文