首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >UVA455「Periodic Strings」

UVA455「Periodic Strings」

作者头像
hotarugali
发布2022-03-02 20:27:47
发布2022-03-02 20:27:47
4990
举报

1. 题目

题目链接:UVA455「Periodic Strings」

Description

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 666 (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 of 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

代码语言:javascript
复制
1
HoHoHo
Sample Output
代码语言:javascript
复制
2

2. 题解

分析

字符串前缀函数的应用水题,结束。

代码

代码语言:javascript
复制
#include <bits/stdc++.h>
using namespace std;

// 前缀函数
struct PrefixFunction {
    #ifndef _PREFIXFUNCTION_
    #define ll int
    #define MAXN 10005
    #endif
    ll pi[MAXN];
    PrefixFunction() {}
    // 计算前缀函数数组
    void getPi(char *str, ll n) {
        pi[0] = 0;
        ll i = 1, j = pi[i-1];
        while(i < n) {
            if(str[i] == str[j]) {
                pi[i++] = j++ + 1;
            } else if(!j) {
                pi[i++] = j;
            } else {
                j = pi[j-1];
            }
        }
    }
};

int main()
{
    ll n;
    char str[MAXN];
    PrefixFunction pf;
    scanf("%d", &n);
    for(ll i = 0; i < n; ++i) {
        scanf("%s", str);
        ll len = strlen(str);
        pf.getPi(str, len);
        if(i) {
            printf("\n");
        }
        ll k = len - pf.pi[len-1];
        printf("%d\n", len%k ? len : k);
    }
    return 0;
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020-09-03,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1. 题目
    • Description
    • Input
    • Output
    • Sample Input
      • Sample Output
  • 2. 题解
    • 分析
    • 代码
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档