动态规划——数字字符串转换为字母组合的种数(decode-ways)
2016-05-24 21:24
423 查看
题目描述
A message containing letters fromA-Zis 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.
例如,当我们知道了n-2长度的字符串能够解释的数目以及n-1长度的字符串能够解释的数目时,我们可以判读如下两个条件:
1)若第n个字符在1到9之间,则n长度的字符串能够解释的数目包含n-1长度字符串能够解释的数目。
2)若第n-1个字符与第n个字符可以解释为一个字母时,则n长度的字符串能够解释的数目包含n-2长度字符串能够解释的数目。
需要注意的地方:
s.charAt(0)不能为0,否则return 0;
public class Solution { public int numDecodings(String s) { if(s == null||s.length() == 0||s.charAt(0) == '0') return 0; if(s.length() == 1) { if(s.charAt(0)!='0') return 1; else return 0; } //dp[i]存放charAt(0)到charAt(i)所能代表的字母组合的个数 int[] dp=new int[s.length()]; dp[0]=1; dp[1]=(s.charAt(1)!='0'?1:0)+((char2int(s.charAt(0))*10+char2int(s.charAt(1)))<=26?1:0); for(int i=2;i<s.length();i++) { if(s.charAt(i)!='0')// dp[i]+=dp[i-1]; if(s.charAt(i-1)!='0'&&(char2int(s.charAt(i-1))*10+char2int(s.charAt(i))<=26)) dp[i]+=dp[i-2]; } return dp[s.length()-1]; } public int char2int(char c) { return c-'0'; } }
相关文章推荐
- Codeforces 610C Harmony Analysis(构造)
- 适用于PHP初学者的学习线路和建议
- js屏蔽
- ant调用shell命令(Ubuntu)
- quick sort analyse
- hdu 1711 Number Sequence -- (KMP 求数列第一匹配的位置)
- project01 PXE 无人职守安装(kickstart|Cobbler)
- equals和==的区别小结
- 输出图像
- c++第六次实验——数组合并
- hellogcc -100GDB技巧
- Java enum(枚举)使用详解
- HDU 5701 (水题)
- 关于智能指针的种种
- 蛇形填数
- PTA fzu_oop_east
- 排序算法之快速排序
- 30学习写论坛-5
- ITGEGE在线教育
- PTA fzu_oop_east