The count-and-say sequence is the sequence of integers with the first five terms as following:
1. 1 2. 11 3. 21 4. 1211 5. 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 term of the count-and-say sequence.
Note: Each term of the sequence of integers will be represented as a string.
Example 1:
Input: 1 Output: "1"
Example 2:
Input: 4 Output: "1211"
方法1:题目意思,依次数上一行重复数字的个数
重复n次,计算上一个string重复char的个数
class Solution {
public:
string countAndSay(int n) {
vector<string> res(n,"");
res[0]="1";
if(n==1) return res[0];
string pre="";
int curindex,count,len;
for(int i=1;i<n;i++){
pre=res[i-1];
len=pre.size();
curindex=0;
count=1;
while(curindex<len){
while(++curindex<len && pre[curindex]==pre[curindex-1]) count++;
res[i]=res[i]+to_string(count)+pre[curindex-1];
count=1;
}
}
return res[n-1];
}
};
注:
1.在while取条件的时候,最好是将0也加入到判断条件中,如果不是从0开始,要注意单独判断
2.转换为string调用to_string函数