File tree Expand file tree Collapse file tree 1 file changed +57
-0
lines changed Expand file tree Collapse file tree 1 file changed +57
-0
lines changed Original file line number Diff line number Diff line change 1+ class Solution :
2+ """
3+ - Time Complexity: O(n), n = len(s)
4+ - Space Complexity: O(n)
5+ """
6+ def numDecodingsDP (self , s : str ) -> int :
7+ if s [0 ] == "0" :
8+ return 0
9+
10+ n = len (s )
11+ dp = [0 ] * (n + 1 )
12+ # dp[0] => empty string => 1 case
13+ # dp[1] => not 0 => 1 case (single digit)
14+ dp [0 ], dp [1 ] = 1 , 1
15+
16+ for i in range (2 , n + 1 ):
17+ one_digit = int (s [i - 1 :i ])
18+ two_digit = int (s [i - 2 :i ])
19+
20+ if 1 <= one_digit <= 9 :
21+ dp [i ] += dp [i - 1 ]
22+ if 10 <= two_digit <= 26 :
23+ dp [i ] += dp [i - 2 ]
24+
25+ return dp [n ]
26+
27+ """
28+ - Time Complexity: O(n), n = len(s)
29+ - Space Complexity: O(1)
30+ """
31+ def numDecodings (self , s : str ) -> int :
32+ if s [0 ] == "0" :
33+ return 0
34+
35+ # Using two variables for checking single and double digit
36+ prev2 , prev1 = 1 , 1
37+
38+ for i in range (1 , len (s )):
39+ current = 0
40+ if s [i ] != "0" :
41+ current += prev1
42+ if 10 <= int (s [i - 1 :i + 1 ]) <= 26 :
43+ current += prev2
44+ prev2 , prev1 = prev1 , current
45+
46+ return prev1 # prev1 = current
47+
48+ tc = [
49+ ("12" , 2 ),
50+ ("226" , 3 ),
51+ ("06" , 0 )
52+ ]
53+
54+ for i , (s , e ) in enumerate (tc , 1 ):
55+ sol = Solution ()
56+ r = sol .numDecodings (s )
57+ print (f"TC { i } is Passed!" if r == e else f"TC { i } is Failed! - Expected: { e } , Result: { r } " )
You can’t perform that action at this time.
0 commit comments