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.
题目的意思是从1开始可以得到11,然后由11得到21,这样继续,现在需要求第n个数字的值。因此需要循环N次来获取第n次的值,初始化以1开始,每一次都对上一次的遍历相邻的重复元素的个数以及元素组成新序列的内容。
class Solution {
public:
string countAndSay(int n) {
string s1 = "1";
if(n==1) return "1";
for(int i=1;i<n;i++)
{
string temp;
char a = s1[0];
int count1 = 1;
for(int j= 1;j<s1.length();j++)
{
if(a == s1[j])
{
++count1;
}else{
stringstream ss;
ss<<count1;
temp += ss.str()+a;
count1 = 1;
a = s1[j];
}
}
stringstream ss;
ss<<count1;
temp += ss.str()+a;
s1 = temp;
}
return s1;
}
};