【leetcode】38. Count and Say(Python & C++)

51 篇文章 1 订阅
50 篇文章 28 订阅

38. Count and Say

题目链接

38.1 题目描述:

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”

38.2 解题思路:

  1. 思路一:首先这道题的意思是口语化计数,比如刚开始1,就是1个1,则为11;11为2个1,则为21;21为1个2,1个1,则为1211;1211为1个1,1个2,2个1,则为111221;以此类推。则很容易用递归的方法解出。首先构造口语化计数的函数,简单的对字符串进行遍历,计数每一个不同的字符的个数,然后返回新的。具体看代码,很简单。

38.3 C++代码:

1、思路一代码(6ms):

class Solution102 {
public:
    string say(string s)
    {
        int l = s.length()-1;
        string t = "";
        int i = 0;
        int count = 1;
        int flag = 0;
        while (i<l)
        {
            if (s[i]==s[i+1])
            {
                count++;
                flag = 0;
            }
            else
            {
                string temp = to_string(count);
                t = t + temp + s[i];
                count = 1;
                flag = 1;
            }
            i++;
        }
        if (flag == 0)
        {
            string temp = to_string(count);
            t = t + temp + s[i];
        }
        else
        {
            t = t + "1" + s[i];
        }
        return t;
    }
    string countAndSay(int n) {
        if (n < 1)
            return "";
        string f="1";
        while (n>1)
        {
            f = say(f);
            n--;
        }
        return f;
    }
};

38.4 Python代码:

1、思路一代码(49ms):

class Solution(object):
    def countAndSay(self, n):
        """
        :type n: int
        :rtype: str
        """
        f="1"
        def say(s):
            i=0
            t=""
            count=1
            flag=0
            while i<len(s)-1:
                if s[i]==s[i+1]:
                    count+=1
                    flag=0
                else:
                    t=t+str(count)+s[i]
                    count=1
                    flag=1
                i+=1
            if flag==0:
                t=t+str(count)+s[i]
            else:
                t=t+"1"+s[i]
            return t
        while n>1:
            f=say(f)
            n-=1
        return f

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值