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.
分析:使用迭代处理,数出相同的,比如“11111”得到4个1,如果是单个“3”就得到1个3。要注意边界处理
class Solution {
public:
string countAndSay(int n) {
string ret = "1";
for(int i = 1; i < n; i++) {
ret = countNext(ret);
}
return ret;
}
string countNext(const string &str) {
string ret;
int count = 1;
char last = str[0];
for(int i = 1; i < str.size(); i++) {
if(str[i] == last) {
count++;
} else {
ret = ret + (char)(count + '0') + last;
count = 1;
last = str[i];
}
}
ret = ret + (char)(count + '0') + last;
return ret;
}
};