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) {
if (n < 1) {
return "";
}
if (n == 1) {
return "1";
}
std::string ret("1");
for (int i = 2; i <= n; i++) {
// we don't need another variable to record
// previous resulted string, as we have it
// as ret (previous result) and stringstream object
// (current result)
std::stringstream newStrSeq;
char last = ret[0];
int count = 0;
// ret[ret.size()] == '\0'
for (int j = 0; j <= ret.length(); j++) {
if (ret[j] == last) {
count++;
} else {
newStrSeq << count << last;
last = ret[j];
count = 1;
}
}
ret = newStrSeq.str();
}
return ret;
}
};