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.
题意:第n个数是第n-1个数的读法。
思路:直接按题意规则count并且say出这个数。注意stringstream的使用会使实现更加方便。
class Solution {
public:
string countAndSay(int n) {
string s;
if (!n)
return s;
s = "1";
n--;
while (n){
stringstream str;
int c=1;
char ch = s[0];
for (int i = 1; i < s.size(); i++){
if (s[i] == s[i - 1])
c++;
else{
str << c;
str << ch;
c = 1;
ch = s[i];
}
}
str << c;
str << ch;
s = str.str();
str.clear();
n--;
}
return s;
}
};