[LeetCode]038-Count And Say

3048 ワード

タイトル:
The count-and-say sequence is the sequence of integers beginning as follows: 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.
Given an integer n, generate the nth sequence.
考え方:文字列をあげて、ルールに従って次の文字列を計算します.初期値を設定したら、n-1回反復すればよい.
コードは次のとおりです.
class Solution {
public:
    string countAndSay(int n) 
    {
        if(n == 0)
            return "";
        else if(n == 1)
            return "1";

        string str = "1";
        n--;
        while(n--)
        {
            str = count(str);
        }
        return str;
    }

    string count(string str)
    {
        int i = 0;
        int n = str.size();
        int count = 1;
        int ch = str[0];
        char str_count[10];
        string result;
        for(i = 1;i<n;i++)
        {
            if(str[i] == ch)
            {
                count++;
            }
            else
            {
                sprintf(str_count,"%d",count);
                result += str_count;
                result += ch;
                ch = str[i];
                count = 1;
            }
        }
        sprintf(str_count,"%d",count);
        result += str_count;
        result += ch;

        return result;
    }
};