Leetcode-Decode Ways(Java)

Question:

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.

Thinking:

If we use the recursive way, we should see that the search tree will go down like check [0],[0,1], then [1],[1,2] and [2],[2,3] then [2], [2,3] and [3],[3,4] and [3],[3,4] and [4],[4,5] … There are some nodes are repeated. So we can use interation from bottom to root to store the number of paths in every index of string.

Solution:

public int numDecodings(String s) {
    int l = s.length();
    if (l == 0)    return 0;
    int[] counts = new int[l+1];

    counts[l] = 1;
    if (s.charAt(l-1) != '0')    counts[l-1] = 1;

    for (int i = l-2; i >=0; i--) {
        if (s.charAt(i) == '0')    continue;
        counts[i] = Integer.parseInt(s.substring(i, i+2)) <=26? counts[i+1]+counts[i+2] : counts[i+1];
    }

    return counts[0];
}

Reference: https://leetcode.com/discuss/8527/dp-solution-java-for-reference