Count and Say

本文介绍了一种有趣的数列生成方法,即数数并报数序列。文章详细解释了如何根据给定的整数n生成该序列的第n项,并提供了一个C++实现示例。

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

每日算法——leetcode系列


问题 Count and Say

Difficulty: Easy

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" or21.
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.

class Solution {
public:
    string countAndSay(int n) {

    }
};

翻译

数数并报数

难度系数:容易

数数并报数顺序按如下规律开始递增:
1,11,21,1211,111221,……

1 读作“1个1”11
11 读作“2个1”21
21 读作“1个21个1”得1211

给定一个整数n,生成第n个序列。

注意:数字序列应该用字符串表示。

思路

此题我觉得英文的表面意思跟实际要的不一样。
题意:数上次字符串中的连续出现数值的个数, 将这些字符串拼接起来

  • n=1时,输出字符串1;
  • n=2时,因为上次字符串1,1连续出现1次,就是1个1,所以输出11;
  • n=3时,由于上次字符串11,其中1连续出现两次,就是2个1,所以输出21;
  • n=4时,由于上次字符串是21,其中2出现1次,1出现1次,所以输出1211;
  • n=5时,由于上次字符串1211,第个1连续出现1次为11,第二个2连续出现1次为12,第三个1跟第四个1连续出现了2次,为21,所以输出111221

代码

#include <iostream>
#include <sstream>
using namespace std;

class Solution {

public:
     string countAndSay(int n) {
        if(n == 1){
            return "1";
        }
        //递归调用
         string str = countAndSay(n-1);
        int len = static_cast<int>(str.length());
        int count = 1;
        stringstream s;
        for(int i = 0; i < len; ++i){
            if(str[i] == str[i+1]){
                count++;
            } else {
                s << count << str[i];

                count = 1;
            }
        }
        return s.str();
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值