LeetCode-decode-ways

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.

public class Solution {
    public int numDecodings(String s) {
        //解题思路:
        //基本是斐波拉契数列dp[i]=dp[i-1]+dp[i-2]
        //dp[i]表示s[0-(i-1)]的解法的个数
        //dp[i-1]表示单独加入新的数字,dp[i-2]表示和前面一个数字凑
        //http://www.cnblogs.com/grandyang/p/4313384.html
        if(s.length() == 0 || s == null || (s.length() > 1 && s.charAt(0)== '0')){
            return 0;
        }
        int[] dp = new int[s.length()+1];
        dp[0] = 1;
        for(int i = 1; i < dp.length; i++){
                //前面一个字符不是'0'则dp[i]至少等于dp[i-1]
                if(s.charAt(i-1) == '0'){
                    dp[i] = 0;
                }else{
                    dp[i] = dp[i-1];
                }
                //判断前一个字符和当前字符是不是可以凑
                if(( i > 1 && s.charAt(i-1)<= '6' && s.charAt(i-2) =='2') || ( i > 1 && s.charAt(i-2) == '1' ) ){
                    dp[i] += dp[i-2];
                }
        }
         
        return dp[s.length()];
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_42146769/article/details/89036429