LeetCode: Decode Ways [090]
来源:互联网 发布:php遍历目录 编辑:程序博客网 时间:2024/06/10 11:23
【题目】
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位,则不能为0),要么是两位(如果是两位,组成的数字必须<=26)。 则给定一个编码串s, 要看字符串到s[i]位置的解码情况,我们只需要知道到s[i-1]和s[i-2]的解码情况。因此这又是一个典型的DP问题。细心的人会发现,这道题其实跟Climbing Stairs本质完全相同,只是换了身马甲。【代码】
class Solution {public: bool isValid(string num){ if(num.length()==1 && num>="1" && num<="9")return true; if(num.length()==2 && num>="10" && num<="26")return true; return false; } int numDecodings(string s) { if(s.length()==0)return 0; if(s.length()==1){ if(isValid(s))return 1; else return 0;//如果第1位为0,不可能解码 } int *decodeWays = new int[s.length()]; //初始化解码到第1位的方案数 if(isValid(s.substr(0,1)))decodeWays[0]=1; else return 0; //初始化解码到第2位的方案数 decodeWays[1] = isValid(s.substr(1,1))?decodeWays[0]:0; decodeWays[1] += isValid(s.substr(0,2))?1:0; if(decodeWays[1]==0)return 0; //不存在解码到这一位的方案 //计算解码到第3~第s.length()位的方案数 for(int i=2; i<s.length(); i++){ decodeWays[i]=isValid(s.substr(i,1))?decodeWays[i-1]:0; decodeWays[i]+=isValid(s.substr(i-1,2))?decodeWays[i-2]:0; if(decodeWays[i]==0)return 0; //不存在解码到这一位的方案 } return decodeWays[s.length()-1]; }};
0 0
- LeetCode: Decode Ways [090]
- Leetcode 91. Decode Ways&&639.Decode ways
- LeetCode: Decode Ways
- [LeetCode]Decode Ways
- LeetCode Decode Ways
- LeetCode : Decode Ways
- [Leetcode] Decode Ways *
- [leetcode] Decode Ways (!!)
- leetcode 17: Decode Ways
- Leetcode: Decode ways
- LeetCode Decode Ways
- [LeetCode]Decode Ways
- [leetcode] Decode Ways
- Leetcode: Decode Ways
- [LeetCode] Decode Ways
- [leetcode]Decode Ways
- LeetCode-Decode Ways
- [leetcode] Decode Ways
- Python初学小结
- jsonp突破同源策略,实现跨域访问请求
- 计算机基础介绍
- 关于python赋值简单例子说明
- iOS性能优化小结
- LeetCode: Decode Ways [090]
- OCP 1Z0 051 154
- 将ntfs分区转换为ext4分区
- 1005. 继续(3n+1)猜想 (25)
- Spring——SSH (Spring+Struts+Hibernate)框架搭建之配置文件序列二
- 过载保护
- orale 查询每年、每月、每日统计量的sql语句
- N-Queens II
- Redis命令总结