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 str;
string seq = "1";
string seqq;
stringstream ss;
int count = 1;
for(int i=2;i<=n;i++) {
for(int j=0;j<seq.size();j++) {
if(seq[j+1]==seq[j])
count++;
else {
ss<<count;
ss>>str;
ss.clear();
seqq+=str;
seqq+=seq[j];
count = 1;
}
}
seq = seqq;
seqq ="";
str = "";
}
return seq;
}
};
编写过程中主要用到了字符串和整形的转换,不熟悉stringstream.clear()导致出现了一些莫名其妙的结果;
在多次转换之前需要用.clear()先清除标志;
参见stringstream的用法