首页 > 代码库 > leetcode 91. Decode Ways

leetcode 91. Decode Ways

leetcode 91. Decode Ways

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.

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.

考虑动态规划,从第二个字符开始,以第i个字符结尾的子字符串的编码方式为dp[i],如果第i个字符不能和第i-1个字符组成10-26之间的数,那么dp[i]=dp[i-1],否则加上dp[i-2]的值(即第i和第i-1的组成一个字符)。

 

public class Solution {
    public int numDecodings(String s) {
        int n=s.length();
        if (n==0) return 0;
        if (s.charAt(0)==‘0‘)return 0;
        int[] dp=new int[n+1];
        dp[0]=1;//没有字符时
        dp[1]=1;//有一个字符时
        for (int i=1;i<n;i++){
            if (s.charAt(i)>=‘1‘&&s.charAt(i)<=‘9‘){
                dp[i+1]=dp[i];
            }
            if (s.charAt(i)>=‘0‘&&s.charAt(i)<=‘6‘&&s.charAt(i-1)==‘2‘){
                dp[i+1]+=dp[i-1];
            }
            if (s.charAt(i)>=‘0‘&&s.charAt(i)<=‘9‘&&s.charAt(i-1)==‘1‘){
                dp[i+1]+=dp[i-1];
            }
        }
        return dp[n];
    }
}

 

leetcode 91. Decode Ways