Decode Ways
2016-04-22 12:03
225 查看
A message containing letters from
using the following mapping:
Given an encoded message containing digits, determine the total number of ways to decode it.
Given encoded message
it could be decoded as
2) or
The number of ways decoding
2.
思路:动态规划
把所给字符串偏历一次,
1、若当前数字(下标为i)为0,则当前数字只能和前一数字结合,而且大于0,小于等于26;
2、若当前数字不为0,则可有两种可能,一种是当前数子单独解码为一个字母,其组合数为(i==0?1:dp[i-1]);第二种是和前一数字组合解码为一个字母,其条件为前一数字不为0,、大于0,小于等于26。当前的组合数为两种可能的组合数之和。
A-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.
Given encoded message
12,
it could be decoded as
AB(1
2) or
L(12).
The number of ways decoding
12is
2.
思路:动态规划
把所给字符串偏历一次,
1、若当前数字(下标为i)为0,则当前数字只能和前一数字结合,而且大于0,小于等于26;
2、若当前数字不为0,则可有两种可能,一种是当前数子单独解码为一个字母,其组合数为(i==0?1:dp[i-1]);第二种是和前一数字组合解码为一个字母,其条件为前一数字不为0,、大于0,小于等于26。当前的组合数为两种可能的组合数之和。
public class Solution { /** * @param s a string, encoded message * @return an integer, the number of ways decoding */ public int numDecodings(String s) { // Write your code here if(s.length()==0) return 0; int[] dp = new int[s.length()]; for(int i=0;i<s.length();++i){ if(Integer.valueOf(s.substring(i,i+1))>0) dp[i] = (i==0? 1 : dp[i-1]); if(i>=1&&s.charAt(i-1)!='0'&&Integer.valueOf(s.substring(i-1,i+1))>0&&Integer.valueOf(s.substring(i-1,i+1))<=26) dp[i] += (i>=2?dp[i-2]:1); if(dp[i]==0) return 0; } return dp[dp.length-1]; } }
相关文章推荐
- 对话框版本低导致异常退出
- 前端知识总结
- iOS const和static详解
- iOS - UIScrollView 显示出来后 偏移64的问题
- tomcat乱码原因--基本的编码问题
- 工作问题-java-利用jsonResult判断返回ajax问题
- My Test about Mat
- zabbix安装
- 64位程序获取CPUID,不使用汇编指令
- Android自动化测试MonkeyRunner(一)------环境搭建
- Mina框架的使用
- 实验二 作业调度
- NDK如何集成libiconv
- 欢迎使用CSDN-markdown编辑器
- 堆排序
- 可变参数宏__VA_ARGS__
- saltstack(六) saltstack Job管理
- 【排序】直接插入排序
- 扩展 vfp9 自带的对象浏览器提取枚举值
- hdu5666 (数学水题)