Count and say[easy on LeetCode]

本文介绍了LeetCode上的Count and Say问题,提供了C++的解题思路和代码实现。该问题生成数列的第n项,通过比较前一项的相邻数字来构建新项。例如,第1项是'1',第2项是'11',第3项是'21'等。解决方案涉及遍历前一项的字符并计算连续重复的字符数量。

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

原题地址:https://leetcode.com/problems/count-and-say/description/

题目描述

The count-and-say sequence is the sequence of integers with the first five terms as following:

  1. 1
  2. 11
  3. 21
  4. 1211
  5. 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 term of the count-and-say sequence.

Note: Each term of the sequence of integers will be represented as a string.

Example 1:

Input: 1
Output: “1”

Example 2:

Input: 4
Output: “1211”

解题思路

首先列出n=1到n=7的结果:
1. 1
2. 11
3. 21
4. 1211
5. 111221
6. 312211
7. 13112221

由题目和输出可以看出,n的结果与n-1的结果有关。
因为n=1属于特殊情况,需要单独赋值。
又因为n=1的输出为1,即个位数,属于特殊情况,所以n=2的结果也需要单独赋值为11。
当n>2时,将n-1得出的字符串代入赋值于一个变量res,并初始化一个空字符串newres。
因为题目中提到需要记录相同字符的数量,所以我们初始化一个变量count=1。
从res的第二位(i)开始,向左一位比较,如果相同,count+1;如果不同,count重置为1。比较完,i+1,重复相同操作。
当 i 移动到res最后一位时(特殊处理),将count和res[ i ]写入newres。

代码实现 in C++:

class Solution {
public:
    string countAndSay(int n) {
        if (n == 1)
            return "1";
        if (n == 2)
            return "11";
        string res = countAndSay(n - 1);
        string newres = "";
        int count = 1;
        for (int i = 1; i < res.size(); ++i) {
            if (res[i] != res[i-1]) {
                newres.push_back('0'+count);
                newres.push_back(res[i-1]);
                count = 1;
            } else {
                count++;
            }
            if (i == res.size() - 1) {
                newres.push_back('0'+count);
                newres.push_back(res[i]);
            }
        }
        return newres;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值