LeetCode之计算解密的数量DecodeWays
2016-07-22 16:14
357 查看
问题描述:
在加密中用‘A’来加密为’1’,’B’加密为’2’.但是在解密时,’12’可能被 解密为’AB’(1,2),也可能被解密为’L’(12)。所以给你一串加密后的数字串,问你有多少种解密的方式。
定义数组C[s.length()+1],C[i+1]表示为:到s[0….i]有C[i+1]种解密的方法。
而且有几个限制的条件:
1、s[i-1]不能等于0,若为0,则C[i]=C[i-2];
2、s[i-1,i-2]的数字只能为1~26之间。
例如:
1010,生成的C数组为:[1,1,1,1,1]
10000,生成的C数组为:[1,1,1,0,0,0,0,0,0]
代码如下:
/** * 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’来加密为’1’,’B’加密为’2’.但是在解密时,’12’可能被 解密为’AB’(1,2),也可能被解密为’L’(12)。所以给你一串加密后的数字串,问你有多少种解密的方式。
定义数组C[s.length()+1],C[i+1]表示为:到s[0….i]有C[i+1]种解密的方法。
而且有几个限制的条件:
1、s[i-1]不能等于0,若为0,则C[i]=C[i-2];
2、s[i-1,i-2]的数字只能为1~26之间。
例如:
1010,生成的C数组为:[1,1,1,1,1]
10000,生成的C数组为:[1,1,1,0,0,0,0,0,0]
代码如下:
public static int numDecodings(String s){ if(s.length()==0) return 0; int[]c=new int[s.length()+1]; c[0]=1; if(s.charAt(0)!='0') c[1]=c[0]; else c[1]=0; for(int i=2;i<=s.length();i++) { if(s.charAt(i-1)=='0') { c[i]=0; }else{ c[i]=c[i-1]; } if(s.charAt(i-2)=='1'||s.charAt(i-2)=='2'&&s.charAt(i-1)<='6') { c[i]+=c[i-2]; } } return c[s.length()]; }
相关文章推荐
- [机器学习笔记]Note11--聚类
- js事件编程的发布/订阅模式(一对一关系)
- mac tomcat: error 1 operation not permitted
- ubuntu 14.04 postgresql 的总结
- Ext.util.Format.date与Ext.Date.format区别, 转换时间戳
- git的版本管理使用(三)-拉取分支代码
- Activity intent经常使用的 FLAG 集合
- sharepoint 2016 学习系列篇(22)-文档库应用篇-(4)给文档添加属性标签
- SICP_Python版第二章:符号数据(简易求导系统)
- spring boot 加载本地静态资源文件路径配置
- 调用系统级别权限(比如修改时间)
- HDU 5727 Necklace (二分图匹配)
- hdu_5734_Acperience
- 高度平衡的二叉树——AVLTree
- 自学 html + css 用到的相关文档
- Java垃圾回收机制
- 括号匹配
- Ubuntu16.04虚拟机使用备注笔记
- CodeForces 387C George and Number
- gradle中用的一些路径环境变量