0
点赞
收藏
分享

微信扫一扫

【每日算法Day 86】面试经典题:把数字翻译成字符串


题目链接

LeetCode 面试题46. 把数字翻译成字符串[1]

题目描述

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

示例1

输入:
12258
输出:
5
解释:
12258有5种不同的翻译,分别是"bccfi", "bwfi", "bczi", "mcfi"和"mzi"


【每日算法Day 86】面试经典题:把数字翻译成字符串_记忆化搜索

代码

c++


class Solution {
public:
int translateNum(int num) {
if (num < 10) return 1;
int res = translateNum(num/10), last = num%100;
if (10 <= last && last <= 25) res += translateNum(num/100);
return res;
}
};


python


class Solution:
def translateNum(self, num: int) -> int:
if num < 10: return 1
res, last = self.translateNum(num//10), num%100
if 10<=last<=25: res += self.translateNum(num//100)
return res


参考资料

[1]

LeetCode 面试题46. 把数字翻译成字符串: ​​https://leetcode-cn.com/problems/ba-shu-zi-fan-yi-cheng-zi-fu-chuan-lcof/​​

举报

相关推荐

0 条评论