[LC] 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 a non-empty string containing only digits, determine the total number of ways to decode it.

Example 1:

Input: "12"
Output: 2
Explanation: It could be decoded as "AB" (1 2) or "L" (12).

class Solution {
    public int numDecodings(String s) {
        int[] arr = new int[s.length() + 1];
        arr[0] = 1;
        // for case of '0';
        arr[1] = s.charAt(0) == '0' ? 0 : 1;
        for (int i = 2; i <= s.length(); i++) {
            int preOne = Integer.valueOf(s.substring(i - 1, i));
            int preTwo = Integer.valueOf(s.substring(i - 2, i));
            if (preOne >= 1 && preOne <= 9) {
                arr[i] += arr[i - 1];
            }
            if (preTwo >= 10 && preTwo <= 26) {
                arr[i] += arr[i - 2];
            }
        }
        return arr[s.length()];
    }
}

猜你喜欢

转载自www.cnblogs.com/xuanlu/p/12047192.html