【作业】外观数列

题目

给定正整数n, 输出外观数列的第n项

结果:

input a num: 4
res: 1211
input a num: 5
res: 111221
input a num: 6
res: 312211
input a num: 1
res: 1
input a num: 2
res: 11
input a num: 3
res: 21
input a num: 4
res: 1211
input a num: 5
res: 111221

代码

事实证明,做题目不要过分考虑内存问题,下面为了避免内存动态分配,搞了两个缓冲区交互来解决,但实际都致不少问题。但实际项目中,必须认真考虑。

#include <iostream>
#include <sstream>
#include <string>
#include <vector>

class CountAndSayTool {

public:
	CountAndSayTool() {
		cur_lst = new int[MAX_COUNT];
		next_lst = new int[MAX_COUNT];
	}
	~CountAndSayTool() {
		delete[] cur_lst;
		delete[] next_lst;
	}

	void _CountAndSay(int* num_lst, const int lst_count, const int cur_n, const int target_n, std::string& res) {
		if (target_n == cur_n) {
			std::stringstream strstr;
			for (int i = 0; i < lst_count; ++i) {
				strstr << num_lst[i];
			}
			res = strstr.str();
			return;
		}

		int* next_num_lst = nullptr;
		int next_count = 0;
		if (lst_count == 0||num_lst ==NULL) {
			next_num_lst = next_lst;
			next_num_lst[0] = 1;
			next_count = 1;
		}else {
			//auto nit = num_lst.begin();
			int cur_index = 0;
			int cur_num = num_lst[0];
			int num_count = 1;
			++cur_index;
			int next_index = 0;
			next_num_lst = this->next_lst;
			for (; cur_index < lst_count; ++cur_index) {
				if (cur_num == num_lst[cur_index]) {
					num_count++;
				}else {
					if (next_index + 1 < MAX_COUNT) {
						next_num_lst[next_index] = num_count;
						++next_index;
						next_num_lst[next_index] = cur_num;
						++next_index;
						cur_num = num_lst[cur_index];
						num_count = 1;
					}else {
						break;
					}
				}
			}
			if (next_index + 1 < MAX_COUNT) {
				next_num_lst[next_index] = num_count;
				++next_index;
				next_num_lst[next_index] = cur_num;
				++next_index;
				cur_num = num_lst[cur_index];
				num_count = 1;
			}
			next_count = next_index;
		}
		int* t = this->cur_lst;
		this->cur_lst = next_lst;
		this->next_lst = t;
		_CountAndSay(next_num_lst, next_count, cur_n + 1, target_n, res);

	}

	static const int MAX_COUNT = 30 * 2;

private:
	int* cur_lst;
	int* next_lst;
	
};

void CountAndSay() {
	CountAndSayTool tool;
	std::string res;
	int n = 1;
	while (n > 0) {
		std::cout << "input a num: ";
		std::cin >> n;
		tool._CountAndSay(NULL, 0, 0, n, res);
		std::cout << "res: " << res << std::endl;
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值