[LeetCode] 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 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.

Thought process:
Dynamic programming.
  1. Sub-problem: determine the total number of ways to decode a sub-string.
  2. Function: iterate through the string from back to beginning.
    1. If s[i] == 0: continue. I can keep f[i] at default value 0 because it would be correct even if s's first character is 0 (return f[0] = 0).
    2. Else:
      1. If s[i, i + 2] <= 26, f[i] = f[i + 1] + f[i + 2].
      2. Else, f[i] = f[i  + 1].
  3. Initialization: f[s.length()] = 1. f[s.length() - 1] = 1 if s's last character is not 0.
  4. Answer: f[0].

Solution:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
    public int numDecodings(String s) {
        int len = s.length();
        if (len == 0) {
            return 0;
        }
        
        int[] f = new int[len + 1];
        f[len] = 1;
        f[len - 1] = s.charAt(len - 1) == '0' ? 0 : 1;
        
        for (int i = len - 2; i >= 0; i--) {
            if (s.charAt(i) == '0') {
                continue;
            }
            if (Integer.parseInt(s.substring(i, i + 2)) <= 26) {
                f[i] = f[i + 1] + f[i + 2];
            } else {
                f[i] = f[i + 1];
            }
        }
        return f[0];
    }
}

Time complexity: O(n).

Comments

Post a Comment

Popular posts from this blog

[LeetCode] 714. Best Time to Buy and Sell Stock with Transaction Fee

[LeetCode] 269. Alien Dictionary

[LeetCode] 631. Design Excel Sum Formula