Decode Ways
来源:互联网 发布:关于php的知识 编辑:程序博客网 时间:2024/04/30 03:41
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.
动态规划来做。
设置动态数组dp[n+1]。dp[i]表示从1~i的decode ways的个数。
当给的code只有一位数时,判断是不是valid(A~Z),是的话就dp[1] = 1 不是的话就是dp[1] = 0
因为像给的例子12可以有两种可能的解析方法,所以计算dp[i]的时候要判断两种可能性,再累加。
isValid()方法主要就是用来判断s那一位或者两位开头是不是0,开头是0的话,对应的少一种可能。
代码如下:public class Solution { public int numDecodings(String s) { //这里的s只出现数字0-9 if(s==null||s.length()==0||s.charAt(0)=='0') return 0; int[] dp = new int[s.length()+1];//java中是可以直接根据变量new出对应长度的数组的。 dp[0] = 1; //初始化dp[0]为了方便计算dp[2] dp[1] = 1; for(int i=2;i<=s.length();i++){ if(isValid(s.substring(i-2,i))){ dp[i] += dp[i-2]; } if(isValid(s.substring(i-1,i))) dp[i] += dp[i-1]; } return dp[s.length()]; } public boolean isValid(String s){ //这个判断方法比较巧妙 if(s.charAt(0)=='0') return false; int temp = Integer.parseInt(s); return temp>=1&&temp<=26; }}
参考出处:http://www.cnblogs.com/springfor/p/3896162.html?utm_source=tuicool
0 0
- Decode Ways
- Decode Ways
- Decode Ways
- Decode Ways
- Decode Ways
- Decode Ways
- Decode Ways
- Decode Ways
- Decode Ways
- Decode Ways
- Decode Ways
- Decode Ways
- Decode Ways
- Decode ways
- Decode Ways
- Decode Ways
- Decode Ways
- Decode Ways
- Android 简易计算器程序
- VGA YUV(YCbCr) YBpBr BNC
- 理解Javascript_07_理解instanceof实现原理
- [LeetCode] Single Number
- leetCode(11):Reverse linked list II
- Decode Ways
- 【Linux&C++】Linux环境下C++编程
- ngx_init_cycle()详解
- Android Canvas绘图详解
- Access数据库技巧汇集
- centos安装配置lnmp
- 关于使用Android Studio 开发NDK项目生成.h文件方法
- android DexClassLoader动态加载技术详解
- servlet交互案例分析及终极实现 使用jdbc连接数据库实现