91. Decode Ways

Description

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.

Solution

这道题用递归会超时,所以还是用DP啦。

DP

注意对于空字符串要返回0。
dp[i] means decode ways of s.substring(0, i)
dp[0] = 1
return dp[n]

class Solution {
    public int numDecodings(String s) {
        if (s == null || s.isEmpty()) {
            return 0;
        }
        
        int n = s.length();
        int[] dp = new int[n + 1];
        dp[0] = 1;
        
        for (int i = 1; i < dp.length; ++i) {
            dp[i] = (isValid(s, i - 1, 1) ? dp[i - 1] : 0)
                + (isValid(s, i - 2, 2) ? dp[i - 2] : 0);
        }
        
        return dp[n];
    }

    private boolean isValid(String s, int i, int digits) {
        if (i < 0) {
            return false;
        }
        
        int val = Integer.parseInt(s.substring(i, i + digits));
        return (digits == 1 && val >= 1 && val <= 9)
            || (digits == 2 && val >= 10 && val <= 26);
    }
}

你可能感兴趣的:(91. Decode Ways)