Count and Say

本文深入解析CountAndSay算法的实现过程,包括数据类型转换、递归逻辑和字符串操作等关键步骤,详细阐述如何从给定整数生成相应的字符串序列。

题目名称
Count and Say—LeetCode链接

描述
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.

分析
返回一个字符串:
当n=1时,返回1;
当n=2时,按照n-1=1返回的值1,读成“1个1”,返回11;
当n=3时,按照n-1=2返回的值11,读成“2个1”,返回21;
当n=4时,按照n-1=3返回的值21,读成“1个2,1个1”,返回1211;
当n=5时,按照n-1=4返回的值1211,读成“1个1,1个2,2个1”,返回111221;
······
这道题一开始不好理解,在看懂题目意思之后,会遇到几个问题:
1.形参为int类型,返回的类型为string,涉及到数据类型转换;
2.第n个返回值要根据第n-1个返回值确定;
3.返回值如何存储来方便计算。
对于这三个问题,分别采用如下方法:
1.stringstream 是 C++ 提供的另一个字串型的串流(stream)物件,它可以实现将整数转换成字符串。要使用 stringstream, 必須先加入這一行:

#include<sstream>

2.定义两个vector,分别保存n-1的返回值和n的返回值。
3.将返回值的各个字符先以int的形式存储在vector中。

       解决了这三个问题,本算法最关键的就是根据n-1的返回值求解n的返回值了,如果n为1时直接返回:当n>1时,先用一个nums存储i=2的各个位,用一个计数器count来计算相同数字出现的次数,temp存储i+1的各个位,然后将temp赋值给nums,让nums保存第i+1个返回值,再利用算法计算出下一个返回值,直到i=n.

C++代码

class Solution {
public:
string countAndSay(int n) {
    stringstream res;
    if(n==1){
        res<<n;
        return res.str();
    }
    int index=0;
    int nums_res=0;
    vector<int> nums(2,1);
    for(int i=2;i<n;i++){
        vector<int> temp;
        int prev=nums[0];
        int count=1;
        for(int j=1;j<nums.size();j++){
            if(nums[j]!=prev){
                temp.push_back(count);
                temp.push_back(prev);
                prev=nums[j];
                count=1;
            }else{
                count++;
            }
            if(j==nums.size()-1){
                temp.push_back(count);
                temp.push_back(prev);
            }
        }
        nums=temp;
    }
    for(int k=0;k<nums.size();k++){
        res<<nums[k];
    }
    return res.str();
}
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值