OJ练习15——T38 Count and Say

【前记】

太感人了T T竟然一次性A了一道T T,恩,淡定淡定。

count-and-say序列如下:
1, 11, 21, 1211, 111221, ...

1 is read off as "one 1" or 11.
11 is read off as "two 1s" or 21.
21 is read off as "one 2, then one 1" or 1211.

给定整数n,输出序列第n个string。

【思路】

想到以前做过的读出一个数的题目。

这道有一点变体,要得到序列第n个值,就要知道其前一个值,这样递推,得知道序列前n个值,所以写一个读出的函数。

读函数设计:

仿照T36,设一个计数数组,记录相同的数字出现的个数,当字符变换时,就输出上一个计数的数值和字符;

输出了以后就将该计数归零。

【my code】

string say(string &s)
{
    int count[9]={0};
    string news;
    int r;
    for(r=0; r<s.size(); r++){
        count[s[r]-'1']++;
        if(r>0&&s[r]!=s[r-1]){
            news.push_back(count[s[r-1]-'1']+'0');
            news.push_back(s[r-1]);
            count[s[r-1]-'1']=0;
        }
    }
    //last push back
    news.push_back(count[s[r-1]-'1']+'0');
    news.push_back(s[r-1]);
    return news;
}
string countAndsay(int n)
{
    string s="1";
    for(int i=0; i<n-1; i++)
        s=say(s);
    return s;
}

亮闪闪的结果:

OJ练习15——T38 Count and SayOJ练习15——T38 Count and Say灯灯等!竟然在c语言的运行速度范围!

【注意】

1.因为每次都输出前一个字符的计数和字符,最后还要补一次。

2.字符计数的方式要学会:count[s[r]-'1']++;

ps:

看了网上别人的,大体一致。