当前位置:网站首页>【JZ46 把数字翻译成字符串】
【JZ46 把数字翻译成字符串】
2022-04-23 14:33:00 【Sugar_wolf】
描述
有一种将字母编码成数字的方式:'a'->1, 'b->2', ... , 'z->26'
。
我们把一个字符串编码成一串数字,再考虑逆向编译成字符串。
由于没有分隔符,数字编码成字母可能有多种编译结果,例如 11
既可以看做是两个 'a'
也可以看做是一个 'k'
。但 10
只可能是 'j'
,因为 0
不能编译成任何结果。
现在给一串数字,返回有多少种可能的译码结果
数据范围:字符串长度满足 0 < n ≤ 90
进阶:空间复杂度 O(n),时间复杂度 O(n)
示例1
输入: "12"
返回值:2
说明:2种可能的译码结果(”ab” 或”l”)
示例2
输入: "31717126241541717"
返回值:192
说明:192种可能的译码结果
分析:
-
首先对数据进行分类,对于空字符串、首字符为
‘0’
的字符串,以及‘0’
的前一位不是‘1’
或者‘2’
的字符串,输出0
; -
建立一个动态数组
dp[len+1]
,用于存储有几种译码结果。dp[0]=1,dp[1]=1。
1)若第k个字符和第
k-1
个字符能够组合成a到z的合法字符,则dp[k+1]=dp[k]+dp[k-1];
2)若无法组成合法字符,则译码结果没有增加,
dp[k+1]=dp[k];
3)若第k个字符和第
k-1
个字符中有‘0’
,则无法产生新的译码方式,dp[k+1]=dp[k]
;
代码:
class Solution {
public:
int solve(string nums) {
int len = nums.size();
if (len == 0)
return 0;
for (int k = 0;k < len;k++)
{
if (nums[k]=='0')
{
if (k == 0)
return 0;
else if (nums[k-1] != '1' && nums[k-1] != '2')
return 0;
}
}//如果0位于第一位或者0的前面不是1或者2,则无法进行译码
int dp[len+1],temp;
dp[0] = 1;
dp[1] = 1;
for (int k=1;k<len;k++)
{
temp=(nums[k]-'0')+(nums[k-1]-'0')*10;
if (temp > 0 && temp <= 26 && nums[k]!= '0'&& nums[k-1] != '0')
dp[k+1] = dp[k]+dp[k-1];
else
dp[k+1] = dp[k];
}
return dp[len];
}
};
运行时间:6ms
超过15.56% 用C++提交的代码
占用内存:424KB
超过46.36%用C++提交的代码
版权声明
本文为[Sugar_wolf]所创,转载请带上原文链接,感谢
https://blog.csdn.net/Sugar_wolf/article/details/124333220
边栏推荐
- TLS/SSL 协议详解 (28) TLS 1.0、TLS 1.1、TLS 1.2之间的区别
- Arduino for esp8266串口功能简介
- On the insecurity of using scanf in VS
- 一款不错的工具:aardio
- Detailed explanation of C language knowledge points -- first knowledge of C language [1]
- 1分钟看懂执行流程,永久掌握for循环(附for循环案例)
- 一个月把字节,腾讯,阿里都面了,写点面经总结……
- LotusDB 设计与实现—1 基本概念
- 51单片机+LCD12864液晶显示的俄罗斯方块游戏,Proteus仿真、AD原理图、代码、论文等
- LLVM - 生成 if-else 以及 PH
猜你喜欢
MDS55-16-ASEMI整流模块MDS55-16
QT interface optimization: QT border removal and form rounding
Processing MKDIR: unable to create directory 'AAA': read only file system
XX project structure notes
AT89C51 MCU digital voltmeter development, measuring range 0 ~ 5V, proteus simulation, schematic diagram, PCB and C program, etc
一款不错的工具:aardio
详解TCP的三次握手
LotusDB 设计与实现—1 基本概念
外包幹了四年,廢了...
本以为能躺着进华为,结果陆续收到京东/滴滴/爱奇艺offer的我迷茫了
随机推荐
Detailed explanation of SAR command
ArrayList collection basic usage
[servlet] detailed explanation of servlet (use + principle)
QT interface optimization: QT border removal and form rounding
tcp_diag 内核相关实现 1 调用层次
顺序栈的基本操作
金九银十,入职字节跳动那一天,我哭了(蘑菇街被裁,奋战7个月拿下offer)
Basic regular expression
Redis cluster 原理
TLS/SSL 协议详解 (28) TLS 1.0、TLS 1.1、TLS 1.2之间的区别
QT actual combat: Yunxi chat room
ssh限制登录的四种手段
机器学习之逻辑回归(Logistic Regression)原理讲解和实例应用,果断收藏
A good tool: aardio
分分钟掌握---三目运算符(三元运算符)
一款不错的工具:aardio
Docker篇 (五) MySQL的安装
IE8 browser prompts whether to block access to JS script
Solve the problem of SSH configuration file optimization and slow connection
flannel 原理 之 TUN模式