思路:
根据第一个推出第二个,第二个推出第三个,以此类推。
时间复杂度为O(N*M),N为轮数,M为每一轮字符串长度。
空间复杂度为O(M)。
class Solution {
public:
string countAndSay(int n) {
if(n == 0) return "";
if(n == 1) return "1";
string base = "1";
string ans;
for(int i = 1; i < n; ++i) {
int len = static_cast<int>(base.size());
for(int j = 0; j < len; ++j) {
int count = 1;
while((j+1<len) && (base[j] == base[j+1])) {
count++;
j++;
}
ans += to_string(count) + base[j];
}
base = ans;
ans.clear();
}
return base;
}
};