UVA 455 Periodic Strings

Problem

https://uva.onlinejudge.org/external/4/455.pdf

Thinking

使用窮舉法, 先測測看cycle=1合不合法在測23…測到跟字串一樣長為止, 若有重複的cycle取最小

Solution

#include<iostream>
#include<string>
using namespace std;
bool isMatch(int cycle, string str)
{    
    for(int i = 0 ; i < str.length(); i+= cycle)
    {
        for(int j = 0 ; j < cycle ; j++)
        {
            if(str[i+j] != str[j])
                return false;
        }
    }

    return true;

}

void solve(string str)
{
    int cycle;

    for(cycle = 1 ; cycle <= str.length() ; cycle++ )
    {
        if(str.length() % cycle != 0)
            continue;

        if(isMatch(cycle, str))
            break;
    }

    cout << cycle << endl;

}


int main()
{   
    int num;
    cin >> num;
    for(int i = 0 ; i < num ; i++)
    {
        //輸出部分需要小心
        if(i != 0)
            cout << endl;

        string str;
        cin >> str;
        solve(str);
    }    

    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章