【Leetcode刷题】把数字翻译成字符串

https://leetcode-cn.com/problems/ba-shu-zi-fan-yi-cheng-zi-fu-chuan-lcof/

递归。

将数字转换为字符串s。翻译字符串s时,我们有两个选择:

  1. 选择将第一位数字翻译成字符。然后翻译剩下的s[1:]
  2. 选择将前两位数字翻译成字符。然后翻译剩下的s[2:]

总的翻译方法的数量应该等于这两部分之和

而其中选择将前两位数字翻译成字符需要一定的条件,这个两位数应该小于或等于25,并且不能是个位数(>=10)

class Solution(object):
    def count(self, s):
        """
        :type s: str
        :rtype: int
        """
        # 小于10的数字只有一种翻译方式
        # 空字符串也算是一种。因为s[2:]是可能为空的
        if len(s) <= 1:
            return 1
        # 选择翻译第一位
        res = self.count(s[1:])
        # 选择翻译前两位
        # 这时需要判断前两位能否翻译为字符
        # 06和6将翻译为同一个字符,因此这种情况不能算作两种翻译方式
        if 10 <= int(s[:2]) <= 25:
            res += self.count(s[2:])
        return res

    def translateNum(self, num):
        """
        :type num: int
        :rtype: int
        """
        # 不希望每次递归都将字符串转为数字
        # 因此写了一个接受字符串作为输入的函数
        return self.count(str(num))

设num = n

时间复杂度:按位遍历了数字num,因此时间复杂度是O(logn)

空间复杂度:将num转换为字符串s,需要O(logn)的空间存储,再加上递归深度为O(logn)。因此总体的空间复杂度为O(logn)

猜你喜欢

转载自www.cnblogs.com/luozx207/p/13204185.html