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;
}
};

本文介绍了一种特殊的整数序列——计数与描述序列,并提供了一个C++实现方案,用于生成序列中的第n项。该序列从1开始,后续每一项都是对其前一项的描述。
493

被折叠的 条评论
为什么被折叠?



