• 紫书第三章练习 uva455 Periodic Strings by crq


    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

    题意:给定一个字符串,它是由某个长度为x的字符串重复若干次产生的,问x的最小值是多少,比如题意中的abcabcabcabc,是由abc重复4次产生的,abc这个字符串的长度为3,所以输出3。

    求解:因为字符串长度最大只有80个字符,因此可以直接暴力解决。这里设将字符串分成i段(i从大到小遍历,从而保证x从小到大遍历),由此求出x的值,并判断每段长度为x的子串是否都一样,只要找到一组即退出,便是x的最小值。

    AC代码:

     1 #include <iostream>
     2 #include <string>
     3 using namespace std;
     4 
     5 int main()
     6 {
     7     string s;
     8     int n;
     9     cin>>n;
    10     for(int t=0;t<n;t++)
    11     {
    12         cin>>s;
    13         int i, len = s.length();
    14         int res = -1;
    15         for(i=len;i>=1;i--)
    16         {
    17             if(len%i==0)
    18             {
    19                 int x = len/i;
    20                 string ss = s.substr(0,x);
    21                 int pos = x, flag = 0;
    22                 while(pos<len)
    23                 {
    24                     string ss2 = s.substr(pos, x);
    25                     if(ss2!=ss)
    26                     {
    27                         flag = 1;
    28                         break;
    29                     }
    30                     pos += x;
    31                 }
    32                 if(flag==0)
    33                 {
    34                     res = x;
    35                     break;                    
    36                 }
    37             }
    38         }
    39         if(res==-1)
    40             res = len;
    41         if(t)
    42             cout<<endl;
    43         cout<<res<<endl;
    44     }
    45     return 0;
    46 }
  • 相关阅读:
    asp.net基础开发中常用代码大全
    IPv6網絡開發范例
    [轉]现场:是谁在住救灾帐篷者?
    运送救灾物资路上的感人画面纪实
    DataGridView新特色、常用操作
    [ZT]定制自己的Windows CE 5.0 ARM中文模拟器
    LoadRunner参数化功能详解
    [轉]灾区那么大,王十为什么直奔遵道镇,不去别处?
    [理想?夢想?]ERP项目怎么管
    乞讨老人为地震灾区捐款105元(图)
  • 原文地址:https://www.cnblogs.com/tzcacm/p/6781851.html
Copyright © 2020-2023  润新知