91. Decode Ways

Difficulty:
Related Topics:
Similar Questions:

Problem

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).

Example 2:

Input: "226"
Output: 3
Explanation: It could be decoded as "BZ" (2 26), "VF" (22 6), or "BBF" (2 2 6).

Solution (Java)

class Solution {
    public int numDecodings(String s) {
        if (s.charAt(0) == '0') {
            return 0;
        }
        int n = s.length();
        int[] f = new int[n + 1];
        // Auxiliary
        f[0] = 1;
        f[1] = 1;
        for (int i = 2; i <= n; i++) {
            // Calculate the independent number
            if (s.charAt(i - 1) != '0') {
                // As long as the current character is not 0, it means that the previous decoding
                // number can be inherited
                f[i] = f[i - 1];
            }
            // Calculate the number of combinations
            int twodigits = (s.charAt(i - 2) - '0') * 10 + (s.charAt(i - 1) - '0');
            if (twodigits >= 10 && twodigits <= 26) {
                f[i] += f[i - 2];
            }
        }
        return f[n];
    }
}

Solution (Javascript)

/**
 * @param {string} s
 * @return {number}
 */
var numDecodings = function(s) {
  var len = s.length;
  var tmp = 0;
  var tmp1 = 1;
  var tmp2 = 0;
  var num1 = 0;
  var num2 = 0;

  if (s === '' || s[0] === '0') return 0;

  for (var i = 1; i <= len; i++) {
    num1 = Number(s.substr(i - 1, 1));
    num2 = Number(s.substr(i - 2, 2));
    if (num1 !== 0) tmp += tmp1;
    if (10 <= num2 && num2 <= 26) tmp += tmp2;
    tmp2 = tmp1;
    tmp1 = tmp;
    tmp = 0;
  }

  return tmp1;
};

Explain:

每个点可由前面一个点 decode 1 一个数字到达或前面两个点 decode 2 个数字到达。

Complexity: