zoukankan      html  css  js  c++  java
  • leetcode 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.

    Example 1:

    Input: 1
    Output: "1"
    

    Example 2:

    Input: 4
    Output: "1211"
    

    class Solution(object):
        def countAndSay(self, n):
            """
            :type n: int
            :rtype: str
            """
            """
            1=>1
            """
            k = "1"
            
            def say(m):
                # greedy
                ans = ""
                c = 1
                for i in xrange(1, len(m)):
                    if m[i] == m[i-1]:
                        c += 1
                    else:
                        ans += str(c) + m[i-1]
                        c = 1
                ans += str(c) + m[-1]
                return ans
                
            for i in xrange(1, n):
                k = say(k)
            return k
            
    

     经典的字符计数问题!或者也可以使用贪心算法求解,还可以避免最后为len-1的判断。

    class Solution(object):
        def countAndSay(self, n):
            """
            :type n: int
            :rtype: str
            """
            """
            1=>1
            """
            k = "1"
            
            def say(m):
                # greedy
                ans = ""     
                i = 0
                while i<len(m):
                    s, c = m[i], 1
                    while i+1<len(m) and m[i+1] == m[i]:
                        i += 1
                        c += 1
                    ans += str(c)+str(s)
                    i += 1
                return ans
                
            for i in xrange(1, n):
                k = say(k)
            return k
            
    
  • 相关阅读:
    Eclipse下,修改MAVEN 中央仓库地址,解决maven下载慢问题
    C语言中头文件string的用法
    Linux中变量$#,$@,$0,$1,$2,$*,$$,$?的含义
    Curl
    LDAP是什么
    Linux网络基本网络配置
    vim
    request,session,cookie的比较
    J2EE开发过程中遇到的问题
    实现弹出登录窗口
  • 原文地址:https://www.cnblogs.com/bonelee/p/9131212.html
Copyright © 2011-2022 走看看