description:

就是看前面那个数有几个几,然后写一串。
Note:

Example:

The count-and-say sequence is the sequence of integers with the first five terms as following:

1.     1
2.     11
3.     21
4.     1211
5.     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.

answer:

class Solution {
public:
    string countAndSay(int n) {
        if (n < 0) return "";
        string res = "1";
        for (int i = 1; i < n; i++) {
            string newres = "";
            for (int k = 0; k < res.size(); ++k) {
                int cnt = 1;
                while(k + 1 < res.size() && res[k] == res[k +1]){
                    cnt += 1;
                    ++k;
                }
                newres += to_string(cnt) + res[k]; 
            }
            res = newres;
        }
        return res;
    }
};

relative point get√:

  • to_string() c++中string类的内置函数

hint :