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.
由于要求出第n个,所以采用循环,对第一个进行计算,得到结果作为第二次循环的输入,一直循环n-1次,循环内部:读取一个值,再向后读相同的值的个数,遇到不同则停下来,将值s[i]和个数n输入到字符串流ss中,最后遍历完,ss转化成string s,作为下次循环的输出。
class Solution {
public:
string countAndSay(int n) {
string s="1";
while(--n){
string tmp="";
int len=s.length();
stringstream ss;
for(int i=0;i<len;){
int j=i;
while(s[i]==s[j]){
j++;
}
int n=j-i;
ss<<n;
ss<<s[i];
i=j;
}
s=ss.str();
}
return s;
}
};
采用递归第n个值就是对第n-1个的操作,对s的处理是不变的,唯一的变化就是将while变成递归。
class Solution {
public:
string countAndSay(int n) {
if(n==1)
return "1";
string s=countAndSay(n-1);
string tmp="";
int len=s.length();
stringstream ss;
for(int i=0;i<len;){
int j=i;
while(s[i]==s[j]){
j++;
}
int n=j-i;
ss<<n;
ss<<s[i];
i=j;
}
s=ss.str();
return s;
}
};