LeetCode 38. Count and Say

本文介绍了一种特殊的整数序列——计数并描述序列,并提供了一种使用C++实现的方法来生成该序列的第n项。通过迭代方式,对当前字符串进行遍历,统计连续相同字符的数量,并将其数量及字符本身添加到新字符串中。

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

38. Count and Say

Description
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.

Analysis
这道题目的意思我其实一开始没看懂,题意比较模糊,容易导致理解错误。
后来才明白,其实题目的意思就是后一个字符串是前一个字符串中每一个连续一样的数字的数量之和加上数字本身。
例如 s1=”1” 有1个1 。所以s2=”11”,表示有1个1,此时s2有2个1。
所以s3 =”21”,表示有2个1。以此类推,一直这样下去。
我的做法就是利用迭代,每一次将数字,对于当前字符串判断其当前字符是否和前一个字符相等,若相等,则count++;
若不相等,则将count中的数字以及当前字符push进新字符串中,更新pre以及count。
这样得到的新字符串就是我们的结果。

Code

class Solution {
public:
    string fun (string s){
        string str;
        int len = s.size();

        char pre = s[0];
        int count = 1 ;
        for(int i = 1 ;i <len;++i){
            if(s[i] == pre) count ++;
            else{
                //str = str + (count + '0');
                char a = '0'+count;
                str +=a;
                str+=pre;
                count =1;
                pre = s[i];
            }
        }
        char a = '0'+count;
        str +=a;
        str+=pre;
        return str;
    }
    string countAndSay(int n) {
        if(n == 0) return "";
        if(n == 1) return "1";

        string s = "1";
        int j = 1;

        while(j<n){
            s = fun(s);
            j++;
        }

        return s;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值