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.
solution:依次读取read string中的值,保存同一数字的出现次数和该数并添加到result string中去,直到read string读完;循环直到找到第n个数
class Solution {
public:
string countAndSay(int n) {
// Note: The Solution object is instantiated only once and is reused by each test case.
if(n <= 0)
return "";
string res = "1";
string cur = "";
vector<int>str(1,0);
for(int cou = 2; cou <= n; cou++)
{
string cur = "";
char curCh = res.at(0);
int count = 1;
int i = 1;
while(i < res.size())
{
if(res.at(i) == curCh)
count ++;
else
{
char ch = '0' + count;
cur = cur + ch;
cur = cur + curCh;
count = 1;
curCh = res.at(i);
}
i++;
}
char ch = '0' + count;
cur = cur + ch;
cur = cur + curCh;
res = cur;
}
return res;
}
};