zoukankan      html  css  js  c++  java
  • TOJ4127: Root of String

    传送门:http://acm.tzc.edu.cn/acmhome/problemdetail.do?&method=showdetail&id=4127

    4127: Root of String
    时间限制(普通/Java):1000MS/3000MS 内存限制:65536KByte

    描述

    The root of string S is a shortest string T such that S=TTTTT...T. That is, you can obtain S by concatenating T with itself many times.

    输入

    Each case has a line with one non-empty string (no more than 255 characters) over the alphabet a,b,c,...,z.

    输出
    For each case, output the root of the string.

    样例输入

    aaaaaa
    ababab
    abca
    样例输出
    a
    ab
    abca

    思路:题意是找字符串的循环节,考虑到循环节的长度只可能是本身长度的因数,即可以从1开始,遍历因数长度的所有情况,如果能找到循环节,那么就输出,如果找不到,那么循环节就是自己本身。

    分割字符串可以调用string类中的substr函数。

    代码:

    #include<iostream>
    #include<algorithm>
    #include<cstdio>
    #include<string>
    using namespace std;
    int main(){
        string s;
        while(cin>>s){
            int a[100],ans = 0;
            for(int i = 1 ; i < s.size() ; i++){
                if(s.size() % i == 0){
                    a[ans++] = i;
                }
            }//循环节肯定是字符串长度的因数 
            int f = 1;//记录是否找到比本身短的字符串作为 循环节 
            for(int i = 0 ; i < ans; i++){//从小到大遍历因数 长度的循环节 
                int flag = 1;//记录是否找到循环节 
                int k = s.size()/a[i]; //记录个数 
                string str[1000];//保存分割的字符串 
                for(int j = 0 ; j < k ; j++){
                    int x = j * a[i];
                    str[j] = s.substr(x,a[i]);
                }
                //从x位置开始,每 a[i]个长度分割字符串,调用substr函数分割字符串 
                for(int j = 1 ; j < k ; j++){
                    if(str[j] != str[j-1]){
                        flag = 0;break;
                    }
                }
                if(flag){
                    f = 0;
                    cout<<str[0]<<endl;
                    break;
                }//遍历分割好的字符串,如果是循环节就输出 
            }
            if(f)cout<<s<<endl;//如果找不到比本身小的循环节,那么自身就是循环节 
        }
    }
  • 相关阅读:
    1.Mybatis的全局配置mybatis-config.xml
    01淘淘商城项目:项目Maven工程搭建
    Connection timed out: connect; Communications link failure
    启动maven项目的配置
    PLSQL 触发器概念
    Git 概念&常用命令
    Git与svn的区别 & Git的工作流程
    Redis 是如何存储的
    Redis 概念,常用命令
    idea 快捷键
  • 原文地址:https://www.cnblogs.com/Esquecer/p/8443231.html
Copyright © 2011-2022 走看看