Decode Ways
来源:互联网 发布:最新轰炸手机短信软件 编辑:程序博客网 时间:2024/05/01 23:51
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.
Given encoded message 12
, it could be decoded as AB
(1 2) or L
(12).
The number of ways decoding 12
is 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]; }}
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
- Cocoapods安装步骤
- iOS之XIB设置边框颜色属性
- 2016年计划
- 南昌.net技术交流QQ群:13721576 欢迎加入!
- 二进制转八进制,八进制转二进制
- Decode Ways
- 三种方式使用vlan (by quqi99)
- JAVA 输出日历
- ionic应用在mac上使用Xcode7.2(7C68)进行iphone真机测试
- max_join_size报错
- phpcms V9 内联/关联链接 字符串较长链接无法正确替换的问题完美解决
- iOS开发数据库篇—SQLite常用的函数
- iOS对图像进行尺寸压缩
- 集群节点临时重启