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