您的位置:首页 > 其它

动态规划——数字字符串转换为字母组合的种数(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';
    }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: