LeetCode: Count and Say

本文详细探讨了使用C++语言实现的复杂数独解题算法,包括回溯法、递归搜索等核心策略。通过具体代码实例,展示了如何高效解决数独谜题,并对算法的时间复杂度和空间复杂度进行了分析。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include<iostream>
#include<vector>
#include<queue>
#include<string>
#include<stdlib.h>
#include <sstream>
#include<windows.h>
using namespace::std;

class Solution {
public:
    string countAndSay(int n) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function

			if(n == 1)
				return "1";
			else
			{
				return pronouce(countAndSay(n - 1).c_str());
			}			
    }

	string pronouce(string value)
	{
		int index = 0;
		string result;
		//stringstream ss;
		//string result;
		int count = 1;
		int size = value.size();
		char cur = value[0];
		for(int i = 1; i < size; i++)
		{
			if(cur == value[i])
			{
				count++;
			}
			else
			{
				result += count + '0';
				result += cur;
				count = 1;
			}
			cur = value[i];
		}
		result += count + '0';
		result += cur;
		return result;
	}
};


Study Point:

巧设起始点,则只要用一个for loop

Round 2:

class Solution {
public:
    string countAndSay(int n) {
        string pre = "1";
        string cur = "";
        for(int i = 2; i <= n; i++)
        {
            char count = '1';
            char say = pre[0];
            for(int j = 1; j < pre.size(); j++)
            {
                if(pre[j] == say)
                    count++;
                else
                {
                    cur = cur + count + say;
                    count = '1';
                    say = pre[j];
                }
            }
            cur = cur + count + say;
            pre = cur;
            cur = "";
        }
        return pre;
    }
};

Round 3:

class Solution {
public:
    string countAndSay(int n) {
        string result = "1";
        n--;
        while(n > 0)
        {
            int l = 0 , r = 0;
            string temp;
            while(l < result.size())
            {
                int count = 0;
                while(r < result.size() && result[r] == result[l])
                {
                    r++;
                    count++;
                }
                temp += to_string(count);
                temp += result[l];
                l = r;
            }
            result = temp;
            n--;
        }
        return result;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值