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;
}
posted @ 2012-09-05 11:44  紫红的泪  阅读(9538)  评论(3编辑  收藏  举报