当前位置:网站首页>剑指Offer46——把数字翻译成字符串
剑指Offer46——把数字翻译成字符串
2022-06-22 13:23:00 【笨笨在努力】
【写在前面】:这道题并不难,但看到题解,发现,自己的代码略显笨拙啊,优秀大佬解题真的高,代码清晰明了,纪念一下差距感(自己递归,回溯还有待加强训练)
原题链接:
剑指 Offer 46. 把数字翻译成字符串 - 力扣(LeetCode)
题目描述:
给定一个数字,我们按照如下规则把它翻译为字符串:0 翻译成 “a” ,1 翻译成 “b”,……,11 翻译成 “l”,……,25 翻译成 “z”。一个数字可能有多个翻译。请编程实现一个函数,用来计算一个数字有多少种不同的翻译方法。
示例 1:
输入: 12258
输出: 5
解释: 12258有5种不同的翻译,分别是"bccfi", "bwfi", "bczi", "mcfi"和"mzi"
解题:第一反应这就是一个青蛙跳台阶(斐波那契数列),只不过是否可以跳两个需要判断一下,如果相邻的两个数介于10-25之间,则可以跳两个,否则不能
思路差不多,可是我解的吧,先把各个位数存起来,然后遍历判断
public int translateNum(int num) {
if (num <= 9) {
return 1;
}
List<Integer> list = new LinkedList<>();
// list中存储从个位开始的各位数
while (num != 0) {
int a = num % 10;
list.add(a);
num /= 10;
}
int[] dp = new int[list.size()];
dp[0] = 1;
// 相邻的两个数,是11-25之间的,可以构成另一种组合,相当于斐波那契
if(list.get(1) == 1){
dp[1] = 2;
}else if(list.get(1) == 2 && list.get(0) < 6){
dp[1] = 2;
}else{
dp[1] = 1;
}
for (int i = 2; i < list.size(); i++) {
if(list.get(i) == 1){
dp[i] = dp[i - 1] + dp[i - 2];
}else if(list.get(i) == 2 && list.get(i - 1) < 6){
dp[i] = dp[i - 1] + dp[i - 2];
}else{
dp[i] = dp[i - 1];
}
}
return dp[list.size() - 1];
}再来看运用递归的:
public int translateNum(int num) {
if(num < 10){
return 1;
}
if((num % 100) >= 10 && (num % 100) <= 25){
return translateNum(num / 10) + translateNum(num / 100);
}else{
return translateNum(num / 10);
}
}边栏推荐
猜你喜欢
随机推荐
一文彻底弄懂建造者模式(Builder)
Is polardbx PG or MySQL?
MadCap Flare 2022,语言或格式的文档
Lisez ceci pour vous apprendre à jouer avec la cible de test de pénétration vulnhub - driftingblues - 5
一文搞懂开放源码软件(OSS)质量保证
数据库中如何使用SQL进行修改&amp;删除
Flink status management
Struggle, programmer -- Chapter 47 the so-called Iraqis are on the water side
看完這篇 教你玩轉滲透測試靶機Vulnhub——DriftingBlues-5
Error: unable to find a match: lrzsz
Shan Zhiguang, chairman of BSN Development Alliance: DDC can provide the underlying support for the development of China's meta universe industry
Data collection: skillfully using Bloom filter to extract data summary
Introduction to groovy syntax
Neuron+ekuiper realizes data collection, cleaning and anti control of industrial Internet of things
Le modèle de diffusion est encore fou! Cette fois - ci, la zone occupée était...
Database employment consulting system for your help
Front and back management system of dessert beverage store based on SSM framework dessert mall cake store [source code + database]
S7-200SMART与FANUC机器人进行Profinet通信的具体方法和步骤
Understand the quality assurance of open source software (OSS)
Maui uses Masa blazor component library









