Skip to content

Latest commit

 

History

History
 
 

91. Decode Ways

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 

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

Companies:
Facebook, Google, Microsoft, Amazon, Salesforce, Uber, Yahoo

Related Topics:
String, Dynamic Programming

Similar Questions:

Solution 1. DP

Denote dp[i] as the result for substring S[0..i] (i[0, N - 1]).

For each letter S[i], we have two options:

  1. Use S[i] to decode. S[i] shouldn't be '0'.
  2. Use S[i - 1] and S[i] to decode. S[i - 1] shouldn't be '0' and the number S[i - 1] and S[i] formed shouldn't be greater than 26.

When dp[i] == 0, we should stop right away and return 0.

dp[i] = 0
dp[i] += dp[i - 1]  if S[i] != '0'
dp[i] += dp[i - 2]  if i != 0 && S[i - 1] != '0' && (S[i - 1] - '0') * 10 + S[i] - '0' <= 26

Since dp[i] only depends on dp[i - 1] and dp[i - 2]. We can reduce the space to just two variables storing dp[i - 1] and dp[i - 2].

// OJ: https://leetcode.com/problems/decode-ways
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(1)
class Solution {
public:
  int numDecodings(string s) {
    int pre2 = 0, pre1 = 1;
    for (int i = 0; i < s.size() && pre1; ++i) {
      int cur = 0;
      if (s[i] != '0') cur += pre1;
      if (i != 0 && s[i - 1] != '0' && (s[i - 1] - '0') * 10 + s[i] - '0' <= 26)
        cur += pre2;
      pre2 = pre1;
      pre1 = cur;
    }
    return pre1;
  }
};