[leetcode] 38. Count and Say

556 篇文章 2 订阅
441 篇文章 0 订阅

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 where 1 ≤ n ≤ 30, 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"

分析

题目的意思是:一开始我没读懂题目的意思,其实就是一个数数字的游戏
最开始是1,然后就是一个一,11;然后是两个一,21;然后是一个二一个一,1211…

  • 理解题目的意思了,递归就很容易解决这个问题了。

C++代码

class Solution {
public:
    string countAndSay(int n) {
        string ans;
        ans="1";
        for(int i=1;i<n;i++){
            solve(ans);
        }
        return ans;
    }
    void solve(string &ans){
        string tmp="";
        int count=1;
        for(int i=0;i<ans.size();i++){
            if(i+1<ans.size()&&ans[i]==ans[i+1]){
                count++;
            }else{
                char ch=count+'0';
                tmp=tmp+ch+ans[i];
                count=1;
            }
        }
        ans=tmp;
    }
};

Python 代码

class Solution:
    def solve(self,res):
        t=''
        count=1
        for i in range(len(res)):
            if i+1<len(res) and res[i]==res[i+1]:
                count+=1
            else:
                t=t+str(count)+str(res[i])
                count=1
        return t

    def countAndSay(self, n: int) -> str:
        res='1'
        for i in range(1,n,1):
            res=self.solve(res)
        return res

下面是另一个版本的代码:

class Solution:
    def countAndSay(self, n: int) -> str:
        res ='1'
        for i in range(n-1):
            cur = ""
            pos = 0
            start = 0

            while pos <len(res):
                while pos < len(res) and res[pos]==res[start]:
                    pos+=1
                cur += str(pos-start)+res[start]
                start = pos
            res = cur
        return res

参考文献

leetCode 38.Count and Say (计数和发言) 解题思路和方法
[编程题]count-and-say

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

农民小飞侠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值