您的位置:首页 > 其它

Decode Ways

2016-04-22 12:03 225 查看
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];
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: