Leetcode 639: Decode Ways II
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 109 + 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
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'.
1 public class Solution { 2 public int NumDecodings(string s) { 3 if (s.Length == 0 || s[0] == '0') return 0; 4 5 long dp0 = 1, dp1 = s[0] == '*' ? 9 : 1; 6 7 for (int i = 1; i < s.Length; i++) 8 { 9 long dp2 = 0; 10 11 if (s[i - 1] == '*') 12 { 13 if (s[i] == '*') 14 { 15 dp2 = dp0 * (9 + 6) + 9 * dp1; 16 } 17 else if ((int)s[i] <= (int)'6') 18 { 19 dp2 = dp0 * 2 + (s[i] == '0' ? 0 : dp1); 20 } 21 else 22 { 23 dp2 = dp0 + dp1; 24 } 25 } 26 else 27 { 28 if (s[i] == '*') 29 { 30 if (s[i - 1] == '1') 31 { 32 dp2 = dp0 * 9 + dp1 * 9; 33 } 34 else if (s[i - 1] == '2') 35 { 36 dp2 = dp0 * 6 + dp1 * 9; 37 } 38 else 39 { 40 dp2 = dp1 * 9; 41 } 42 } 43 else 44 { 45 var decode = ((int)s[i - 1] - (int)'0') * 10 + ((int)s[i] - (int)'0'); 46 if (decode >= 10 && decode <= 26) 47 { 48 dp2 = dp0; 49 } 50 51 if (decode % 10 != 0) 52 { 53 dp2 += dp1; 54 } 55 } 56 57 } 58 59 dp0 = dp1 % (1000000007); 60 dp1 = dp2 % (1000000007); 61 } 62 63 return (int)(dp1 % (1000000007)); 64 } 65 }