题目
算法
O(n)
- 对于前一个数,找出相同的元素个数,把个数和该元素存入新的string
代码
class Solution {
public:
string countAndSay(int n) {
if (n <= 0) return NULL;
string res = "1";
for (int i = 1; i < n; ++i) {
string tmp;
res.push_back('$'); // Add extra char to deal with boundary
int count = 0;
int len = strlen(res.c_str());
for (int j = 0; j < len; ++j) {
if (j == 0) ++count;
else {
if (res[j] != res[j - 1]) {
tmp.push_back(count + '0');
tmp.push_back(res[j - 1]);
count = 1;
} else ++count;
}
}
res = tmp;
}
return res;
}
};