[LeetCode] Decode Ways II

639. Decode Ways II

A message containing letters from A-Z can be encoded into numbers using the following mapping:

1
2
3
4
'A' -> "1"
'B' -> "2"
...
'Z' -> "26"

To decode an encoded message, all the digits must be grouped then mapped back into letters using the reverse of the mapping above (there may be multiple ways). For example, “11106” can be mapped into:

  • “AAJF” with the grouping (1 1 10 6)
  • “KJF” with the grouping (11 10 6)

Note that the grouping (1 11 06) is invalid because “06” cannot be mapped into ‘F’ since “6” is different from “06”.

In addition to the mapping above, an encoded message may contain the ‘‘ character, which can represent any digit from ‘1’ to ‘9’ (‘0’ is excluded). For example, the encoded message “1“ may represent any of the encoded messages “11”, “12”, “13”, “14”, “15”, “16”, “17”, “18”, or “19”. Decoding “1*” is equivalent to decoding any of the encoded messages it can represent.

Given a string s consisting of digits and ‘*’ characters, return the number of ways to decode it.

Since the answer may be very large, return it modulo 109 + 7.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
class Solution {
long long dp[100001];
long long mod = 1e9 + 7;
long long helper(string& s, int p) {
if(p > s.length()) return 0;
if(s.length() == p) return 1;
if(s[p] == '0') return 0;
if(dp[p] != -1) return dp[p];
long long& res = dp[p] = 0;

if(s[p] == '*') {
if(p + 1 == s.length()) return res = 9;
if(s[p + 1] == '*') {
res = (9 * helper(s, p + 1) % mod + 15 * helper(s, p + 2) % mod) % mod;
} else if(s[p + 1] <= '6') {
res = (9 * helper(s, p + 1) % mod + 2 * helper(s, p + 2) % mod) % mod;
} else {
res = (9 * helper(s, p + 1) % mod + helper(s, p + 2) % mod) % mod;
}
} else if(s[p] == '1') {
if(p + 1 == s.length()) return res = 1;
if(s[p + 1] == '*') {
res = (helper(s, p + 1) + 9 * helper(s, p + 2) % mod) % mod;
} else {
res = (helper(s, p + 1) + helper(s, p + 2)) % mod;
}
} else if(s[p] == '2') {
if(p + 1 == s.length()) return res = 1;
if(s[p + 1] == '*') {
res = (helper(s, p + 1) + 6 * helper(s, p + 2) % mod) % mod;
} else if(s[p + 1] <= '6') {
res = (helper(s, p + 1) + helper(s, p + 2)) % mod;
} else res = helper(s, p + 1);

} else res = helper(s, p + 1);

return res;
}
public:
int numDecodings(string s) {
memset(dp, -1, sizeof dp);
return helper(s, 0);
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/25/PS/LeetCode/decode-ways-ii/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.