问题
https://leetcode.com/problems/count-and-say/
解法
模拟法, n=100都会超时。
class Solution {
public:
string countAndSay(int n) {
string ret;
ret.push_back('1');
for (int i=2; i<=n; ++i){
string now;
int cnt =1;
for (int j=1; j< ret.size(); ++j)
{
if (ret[j] != ret[j-1])
{
now.append(to_string(cnt));
now.push_back(ret[j-1]);
cnt = 1;
}else cnt++;
}
now.append(to_string(cnt));
now.push_back(ret[ret.size()-1]);
ret = now;
}
return ret;
}
};
int 转 string to_string
string 转 int stoi
本文提供了一个LeetCode上计数与说数问题的有效解决方案。通过使用C++实现的一种模拟方法,详细介绍了如何生成第n项的计数与说数序列。此方法适用于较小的n值,并探讨了当n增大时可能出现的时间效率问题。
637

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



