1. 程式人生 > >Periodic Strings KMP next 陣列 求 迴圈節

Periodic Strings KMP next 陣列 求 迴圈節

455 - 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

曾經做過這種通過next陣列求迴圈節的問題,方法還是這樣:

    1.求出next陣列,字串的長度為len

    2.迴圈節的長度cyclic=len-next[len]

    3.如果next[len]==0或者len%cyclic!=0,即迴圈節的個數不是整數個,那麼迴圈節長度就是len

有一個很重要的就是最後一個回車不要出輸出,否則會WA,因為這個錯了n次,以往會有PE提醒,這也告訴我們要嚴格按照題目的要求輸出。

#include <iostream>
#include <stdio.h>
#include <string.h>
#define MAX 100
using namespace std;

int next[MAX];
char str[MAX];
int len;
void get_next()
{
    int j,k;
    j=0,k=-1;
    next[0]=-1;
    while(j<len)
    {
        if(k==-1||str[j]==str[k])
        {
            j++,k++;
            next[j]=k;
        }
        else
            k=next[k];
    }
    if(next[len]==-1)
        next[len]=0;
}

void show()
{
    for(int i=0;i<=len;i++)
    {
        printf("%d ",next[i]);
    }
    printf("\n");
}

int main()
{
    int n,cyclic;
    scanf("%d",&n);
    getchar();
    while(n--)
    {
        scanf("%s",str);
        len=strlen(str);
        get_next();
        cyclic=len-next[len];
        show();
        if(next[len]==0||len%cyclic!=0)
            printf("%d\n",len);
        else
            printf("%d\n",cyclic);
        if(n)
            printf("\n");

    }
    return 0;
}