天天看点

剑指 Offer 46. 把数字翻译成字符串 python剑指 Offer 46. 把数字翻译成字符串

剑指 Offer 46. 把数字翻译成字符串

剑指 Offer 46. 把数字翻译成字符串 python剑指 Offer 46. 把数字翻译成字符串
class Solution(object):
    def translateNum(self, num):
        """
        :type num: int
        :rtype: int
        """
        if num == 0:
            return 1
        # 将数字按每一位转换为数组
        nums = []
        while num:
            nums.append(num % 10)
            num = num // 10
        nums = nums[::-1]

        counts = [0 for i in range(len(nums))] # 存历史信息
        for i in range(len(nums)-1, -1, -1):
            count = 0
            if i+1 < len(nums):
                # 该数字单独表示
                count += counts[i+1]
            else:
                count += 1
            if i+1<len(nums) and 10<=(nums[i]*10+nums[i+1])<=25:
                # 该数字和下一个数字可以构成一组
                if i+2 < len(nums):
                    count += counts[i+2]
                else:
                    count += 1
            counts[i] = count
        return counts[0]