I'm posting my code for a LeetCode problem copied here. If you would like to review, please do so. Thank you for your time!
Problem
A message containing letters from A-Z is being encoded to numbers using the following mapping way:
'A' -> 1 'B' -> 2 ... 'Z' -> 26
Beyond that, now the encoded string can also contain the character '*', which can be treated as one of the numbers from 1 to 9.
Given the encoded message containing digits and the character '*', return the total number of ways to decode it.
Also, since the answer may be very large, you should return the output mod \$10^9 + 7\$.
Example 1:
- Input: "*"
- Output: 9
- Explanation: The encoded message can be decoded to the string: "A", "B", "C", "D", "E", "F", "G", "H", "I".
Example 2:
- Input: "1*"
- Output: 9 + 9 = 18
Example 3:
- Input: "2*"
- Output: 15
Example 4:
- Input: "3*"
- Output: 9
Example 5:
- Input: "44*4"
- Output: 11
Note:
- The length of the input string will fit in range [1, 105].
- The input string will only contain the character '*' and digits '0' - '9'.
Code
#include <string>
#include <vector>
class Solution {
static constexpr size_t MOD = 1e9 + 7;
public:
static size_t numDecodings(const std::string message);
static size_t decode(const char a_num_ast);
static size_t decode(const char a_num_ast, const char b_num_ast);
};
inline size_t Solution::decode(const char a_num_ast) {
if (a_num_ast == '*') {
return 9;
} else if (a_num_ast == '0') {
return 0;
} else {
return 1;
}
}
inline size_t Solution::decode(const char a_num_ast, const char b_num_ast) {
if (a_num_ast == '1') {
if (b_num_ast == '*') {
return 9;
} else if (b_num_ast >= '0' && b_num_ast <= '9') {
return 1;
}
} else if (a_num_ast == '2') {
if (b_num_ast == '*') {
return 6;
} else if (b_num_ast >= '0' && b_num_ast <= '6') {
return 1;
}
} else if (a_num_ast == '0') {
return 0;
} else if (a_num_ast == '*') {
return decode('1', b_num_ast) + decode('2', b_num_ast);
}
return 0;
}
inline size_t Solution::numDecodings(const std::string message) {
const size_t length = message.size();
std::vector<size_t> decodes_dp(3, 0);
decodes_dp[0] = 1;
decodes_dp[1] = decode(message[0]);
for (size_t index = 2; index <= length; index++) {
decodes_dp[index % 3] = (decodes_dp[(index - 1) % 3] * decode(message[index - 1]) % MOD +
decodes_dp[(index - 2) % 3] * decode(message[index - 2], message[index - 1]) % MOD) % MOD;
}
return decodes_dp[length % 3];
}