1
+ /*
2
+ * Implementation of Decode Ways II problem from LeetCode(Hard)
3
+ *
4
+ * Problem link: https://leetcode.com/problems/decode-ways-ii/
5
+ *
6
+ * Time Complexity: O(n)
7
+ * Space Complexity: O(n)
8
+ */
9
+
10
+ import java .util .*;
11
+ import java .io .*;
12
+
13
+ class DecodeWaysII
14
+ {
15
+ public int numDecodings (String s )
16
+ {
17
+ long [] dp =new long [s .length ()+1 ];
18
+ dp [0 ]=1 ;
19
+ dp [1 ]= decodeChar (s .charAt (0 ));
20
+ for (int i =2 ;i <=s .length ();i ++)
21
+ {
22
+
23
+ char prev =s .charAt (i -2 );
24
+ char curr =s .charAt (i -1 );
25
+
26
+ //single character decoding
27
+ dp [i ] += dp [i -1 ]*decodeChar (curr );
28
+
29
+ //double character decoding
30
+ dp [i ] += dp [i -2 ]*decodeTwoChars (prev , curr );
31
+
32
+ dp [i ] = dp [i ]%1000000007 ;
33
+ }
34
+ return (int )dp [s .length ()];
35
+ }
36
+
37
+ private int decodeChar (char c )
38
+ {
39
+ if (c =='*' )
40
+ return 9 ;
41
+ else if (c =='0' )
42
+ return 0 ;
43
+
44
+ return 1 ;
45
+ }
46
+
47
+ private int decodeTwoChars (char first , char second )
48
+ {
49
+ switch (first )
50
+ {
51
+ case '*' :
52
+ if (second == '*' )
53
+ return 15 ;
54
+ else if (second >='0' && second <='6' )
55
+ return 2 ;
56
+ else
57
+ return 1 ;
58
+
59
+ case '1' :
60
+ if (second == '*' )
61
+ return 9 ;
62
+ else
63
+ return 1 ;
64
+
65
+ case '2' :
66
+ if (second == '*' )
67
+ return 6 ;
68
+ else if (second >= '0' && second <= '6' )
69
+ return 1 ;
70
+ else
71
+ return 0 ;
72
+ default :
73
+ return 0 ;
74
+ }
75
+ }
76
+
77
+ public static void main (String args [])
78
+ {
79
+ Scanner sc = new Scanner (System .in );
80
+ String str = sc .nextLine ();
81
+ DecodeWaysII ob = new DecodeWaysII ();
82
+ System .out .println (ob .numDecodings (str ));
83
+ }
84
+ }
85
+
86
+ /*
87
+ * Example 1:
88
+
89
+ Input: s = "*"
90
+ Output: 9
91
+ Explanation: The encoded message can represent any of the encoded messages "1", "2", "3", "4", "5", "6", "7", "8", or "9".
92
+ Each of these can be decoded to the strings "A", "B", "C", "D", "E", "F", "G", "H", and "I" respectively.
93
+ Hence, there are a total of 9 ways to decode "*".
94
+
95
+ Example 2:
96
+
97
+ Input: s = "1*"
98
+ Output: 18
99
+ Explanation: The encoded message can represent any of the encoded messages "11", "12", "13", "14", "15", "16", "17", "18", or "19".
100
+ Each of these encoded messages have 2 ways to be decoded (e.g. "11" can be decoded to "AA" or "K").
101
+ Hence, there are a total of 9 * 2 = 18 ways to decode "1*".
102
+
103
+ Example 3:
104
+
105
+ Input: s = "2*"
106
+ Output: 15
107
+ Explanation: The encoded message can represent any of the encoded messages "21", "22", "23", "24", "25", "26", "27", "28", or "29".
108
+ "21", "22", "23", "24", "25", and "26" have 2 ways of being decoded, but "27", "28", and "29" only have 1 way.
109
+ Hence, there are a total of (6 * 2) + (3 * 1) = 12 + 3 = 15 ways to decode "2*".
110
+ */
0 commit comments