Count and Say

C++

递归

class Solution
{
  public:
    string countAndSay(int n)
    {
        if (n == 1)
            return "1";
        else if (n == 2)
            return "11";
        else
        {
            string temp = countAndSay(n - 1);
            string result = "";
            int count = 1;
            int n = temp.size();
            char ch = temp[n - 1];
            for (int i = n - 2; i >= 0; i--)
            {
                if (temp[i] != ch)
                {
                    result = to_string(count) + ch + result;
                    count = 1;
                    ch = temp[i];
                }
                else
                {
                    count++;
                }
            }
            result = to_string(count) + ch + result;
            return result;
        }
    }
};

faster

stringstream

  • 头文件:sstream

python

使用正则表达式1

使用正则表达式2

使用groupby

Last updated

Was this helpful?