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. 1
2. 11
3. 21
4. 1211
5. 111221
6. 312211
7. 13112221
8. 1113213211
9. 31131211131221
10. 13211311123113112211
class Solution {
public:
string countAndSay(int n) {
if(n == 0) return "";
int cnt = 1;
string res = "1";
while(--n){
string cur = "";
int x = res.size();
for(int i = 0; i < x; ++i){
if(i < x-1 && res[i] == res[i+1])
cnt++;
else{
cur += to_string(cnt);
cur += res[i];
cnt = 1;
}
}
res = cur;
}
return res;
}
};
本文介绍了一种特殊的整数序列——计数与描述序列,并提供了一个C++实现方案来生成该序列的第n项。计数与描述序列从1开始,后续每一项都是对其前一项的描述。
637

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



