1. 题目
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.
2. 思路
迭代重复即可
3. 代码
耗时:3ms
#include <sstream>
class Solution {
public:
string countAndSay(int n) {
string s = "1";
while (--n != 0) {
s = foo(s);
}
return s;
}
string foo(string& s) {
string ret;
int len = s.length();
if (len == 0) {return ret;}
char last = s[0];
int cnt = 1;
stringstream ss;
for (int i = 1; i < len; i++) {
if (s[i] != last) {
ss << cnt << last;
last = s[i];
cnt = 1;
} else {
cnt++;
}
}
ss << cnt << last;
return ss.str();
}
};
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。