题目:
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.
Note: The sequence of integers will be represented as a string.
class Solution {
public:
string countAndSay(int n) {
string res;
if (n < 0) return res;
res = "1";
for (int i = 1; i < n; ++i){
string tmp;
int j = 0;
int cnt = 0;
for (; j < res.size(); ++j){
if (j == 0 || res[j] == res[j - 1]) {
<span style="white-space:pre"> </span>++cnt;
<span style="white-space:pre"> </span>continue;
<span style="white-space:pre"> </span>}
tmp.push_back(cnt + '0');//前一个字符的个数
tmp.push_back(res[j - 1]);//前一个字符
cnt = 1;//!!!当前的字符个数是1个
}
//!!!最后一组
tmp.push_back(cnt + '0');
tmp.push_back(res[j - 1]);
res = tmp;
}
return res;
}
};
注意:
在当前字符不同于前一个字符时才可以确定前一组