• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录

nunca

但行好事 莫问前程
  • 博客园
  • 联系
  • 订阅
  • 管理

公告

View Post

LeetCode Easy: 38. Count and Say

一、题目

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.

二、解题思路

题目的意思就是:“计数”和“说数”,后一个就是前一个的表达,如果1211,就是:1个1,1个2,两个1,写出来就是111221。给定字符串是 s,相邻的相等的子串进行计数,结果为 str(count)+str[ i ]

三、代码

#coding:utf-8
def countStr(strs):
    counts = 0
    s = ""
    i = 0

    while i in range(len(strs)):  #遍历字符串
        for j in range(i,len(strs)):    #遍历当前字符之后的字符
            if strs[j] != strs[i]:      
                counts = j - i
                s = s + str(counts) + strs[i]
                break
            if j == len(strs)-1:     # 到最后一个字符时,应该单独考虑,因为python中的range范围包左不包右
                counts = j -i + 1
                s = s + str(counts) + strs[i]
        i = i+counts
    print(s)
    return s

def countAndSay(n):
    """
    :type n: int
    :rtype: str
    """
    if n == 1:
        print(1)
        return 1
    s = '1'
    while n > 1:
        s = countStr(s)
        n -= 1
    return s

if __name__ == '__main__':
    countAndSay(10)

四、“别人”代码

http://www.cnblogs.com/chruny/p/4926290.html

class Solution(object):
    def countStr(self,s):
        count = 0;ans = "";tmp = s[0]
        for i in range(len(s)):
            if s[i] == tmp:
                count += 1
            else:
                ans += str(count) + tmp
                tmp = s[i];count = 1
        ans += str(count) + tmp
        return ans
    def countAndSay(self, n):
        """
        :type n: int
        :rtype: str
        """
        ans = '1'
        while n > 1:
            ans = self.countStr(ans)
            n -= 1
        return ans

 

既然无论如何时间都会过去,为什么不选择做些有意义的事情呢

posted on 2018-03-25 10:15  乐晓东随笔  阅读(146)  评论(0)    收藏  举报

刷新页面返回顶部
 
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3