Count and Say


    题意是n=1时输出字符串1;n=2时,数上次字符串中的数值个数,因为上次字符串有1个1,所以输出11;n=3时,由于上次字符是11,有2个1,所以输出21;n=4时,由于上次字符串是21,有1个2和1个1,所以输出1211。依次类推,写个countAndSay(n)函数返回字符串。

string unguarded_convert(const string &say)
{
    stringstream ss;
    int count = 0;
    char last = say[0];
    
    for (size_t i = 0; i <= say.size(); ++i)
    {
        if (say[i] == last)
        {
            ++count;
        }
        else
        {
            ss << count << last;
            count = 1;
            last = say[i];
        }
    }
    
    return ss.str();
}
 
string countAndSay(int n) 
{
    if (n <= 0) return string();
    
    string say = "1";
    
    for (int i = 1; i < n; ++i)
    {
        say = unguarded_convert(say);
    }
    
    return say;
}


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM