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

题目:

给定一个数字,我们按照如下规则把它翻译为字符串:
0翻译成”a”,1翻译成”b”,……,11翻译成”l”,……,25翻译成”z”。一个数字可能有多个翻译。例如12258有5种不同的翻译,它们分别是”bccfi”、”bwfi”、”bczi”、”mcfi”和”mzi”。请编程实现一个函数用来计算一个数字有多少种不同的翻译方法。

解答:

class Solution:
    def getTranslationCount(self, s):
        """
        :type s: str
        :rtype: int
        """
        if not s:
            return 0
        self.d = {}
        return self.count(s)
        
    def count(self, s):
        if len(s) <= 1:
            if s not in self.d:
                self.d[s] = 1
                return 1
        else:
            if 10 <= int(s[0])*10 + int(s[1]) <= 25:
                n = self.d.get(s[1:],self.count(s[1:])) + self.d.get(s[2:], self.count(s[2:]))
                if s not in self.d:
                    self.d[s] = n
                return n
            else:
                n = self.d.get(s[1:],self.count(s[1:]))
                if s not in self.d:
                    self.d[s] = n
                return n 
class Solution {
public:
    int GetTranslationCount(int number) {
        if (number < 0)
            return 0;

        string numberInString = to_string(number);
        return GetTranslationCount(numberInString);
    }

    int GetTranslationCount(const string& number) {
        int length = number.length();
        int* counts = new int[length];
        int count = 0;
        for (int i = length - 1; i >= 0; i--) {
            count = 0;
            if (i < length - 1)
                count = counts[i + 1];
            else
                count = 1;

            if (i < length - 1) {
                int digit1 = number[i] - '0';
                int digit2 = number[i + 1] - '0';
                int converted = digit1 * 10 + digit2;
                if (converted >= 10 && converted <= 25) {
                    if (i < length - 2)
                        count += counts[i + 2];
                    else
                        count += 1;
                }
            }
            counts[i] = count;
        }
        count = counts[0];
        delete[] counts;

        return count;
    }

};

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值