leetcode || 91、Decode Ways
来源:互联网 发布:an软件 编辑:程序博客网 时间:2024/05/21 06:49
problem:
A message containing letters from A-Z
is being encoded to numbers using the following mapping:
'A' -> 1'B' -> 2...'Z' -> 26
Given an encoded message containing digits, determine the total number of ways to decode it.
For example,
Given encoded message "12"
, it could be decoded as "AB"
(1 2) or "L"
(12).
The number of ways decoding "12"
is 2.
题意:A~Z分别编码到1~26,反过来,1~26也可以解码到A~Z,给定一个包含0~9的字符串,求其解码到包含A~Z的字符串的方式有多少
thinking:
(1)这道题很经典,很考察 DP、边界条件,我调试了一个小时才 AC
(2)这道题不是要一一列出解码出来的字符串,而是求解码的方法数。采用深搜的方法可以一一打印出来解码后的字符串,但是对于该题时间复杂度坑定会超时。
(3)采用DP,开一个n大小的数组记录DP的最优子结构的解。DP的难点在于寻找状态转移方程
if(s.at(i)=='0') { if(s.at(i-1)=='1'||s.at(i-1)=='2') { a[i]=a[i-2]; continue; } else return 0; } if(s.at(i-1)=='1' ||(s.at(i-1)=='2'&&(s.at(i)>'0'&&s.at(i)<'7')) ) a[i]=a[i-2]+a[i-1]; else a[i]=a[i-1];从左往右遍历字符串,对于第i个数字怎么解码,要看第i、i-1能否一起解码。
例如,当我们知道了n-2长度的字符串能够解释的数目以及n-1长度的字符串能够解释的数目时,我们可以判读如下两个条件:
1)若第n个字符在1到9之间,则n长度的字符串能够解释的数目包含n-1长度字符串能够解释的数目。
2)若第n-1个字符与第n个字符可以解释为一个字母时,则n长度的字符串能够解释的数目包含n-2长度字符串能够解释的数目。
code:
class Solution {public: int numDecodings(string s) { int n=s.size(); vector<int> a(n,0); if(n==0) return 0; if(s.at(0)=='0') return 0; if(n==1) return 1; a[0]=1; if(s.at(1)=='0') { if(s.at(0)=='1' || s.at(0)=='2') a[1]=1; else a[1]=0; } else if(s.at(0)=='1' || (s.at(0)=='2'&&(s.at(1)>'0'&&s.at(1)<'7'))) a[1]=2; else a[1]=1; if(n==2) return a[1]; for(int i=2;i<n;i++) { if(s.at(i)=='0') { if(s.at(i-1)=='1'||s.at(i-1)=='2') { a[i]=a[i-2]; continue; } else return 0; } if(s.at(i-1)=='1' ||(s.at(i-1)=='2'&&(s.at(i)>'0'&&s.at(i)<'7')) ) a[i]=a[i-2]+a[i-1]; else a[i]=a[i-1]; } return a[n-1]; }};
0 0
- LeetCode 91: Decode Ways
- [leetcode 91] Decode Ways
- [LeetCode 91]Decode Ways
- leetcode || 91、Decode Ways
- Leetcode 91 Decode Ways
- LeetCode(91) Decode Ways
- leetcode 91:Decode Ways
- Leetcode #91 Decode Ways
- leetcode 91: Decode Ways
- LeetCode 91: Decode Ways
- 【leetcode】【91】Decode Ways
- [LeetCode-91] Decode Ways
- leetcode 91 Decode Ways
- LeetCode 91 Decode Ways
- Leetcode 91 Decode Ways
- Leetcode(91) Decode Ways
- Leetcode Decode Ways 91
- LeetCode 91 Decode Ways
- 在Eclipse中使用JUnit4进行单元测试(高级篇)
- Android开发初学者常见问题(不断更新)
- iOS:(boundingRectWithSize)按大小计算字符串高度
- Error: Cannot retrieve metalink for repository: epel. Please verify its path and try again
- Flume配置
- leetcode || 91、Decode Ways
- 如何上传jar包至Maven私服
- 再造 “手机QQ” 侧滑菜单(三)——视图联动
- 10大游戏显存占用率测试
- BZOJ 2648 SJY摆棋子 K-Dimensional-Tree
- android.os.NetworkOnMainThreadException
- 核函数(Kernels)
- Spring 的 BeanPostProcessor接口实现
- linux下select函数总结