File tree Expand file tree Collapse file tree 1 file changed +60
-0
lines changed
December_LeetCode_Challenge Expand file tree Collapse file tree 1 file changed +60
-0
lines changed Original file line number Diff line number Diff line change 1+ A message containing letters from A - Z is being encoded to numbers using the following mapping :
2+
3+ 'A' - > 1
4+ 'B' - > 2
5+ ...
6+ 'Z' - > 26
7+ Given a non - empty string containing only digits , determine the total number of ways to decode it .
8+
9+ The answer is guaranteed to fit in a 32 - bit integer .
10+
11+
12+ Example 1 :
13+ Input : s = "12"
14+ Output : 2
15+ Explanation : It could be decoded as "AB" (1 2 ) or "L" (12 ).
16+
17+ Example 2 :
18+ Input : s = "226"
19+ Output : 3
20+ Explanation : It could be decoded as "BZ" (2 26 ), "VF" (22 6 ), or "BBF" (2 2 6 ).
21+
22+ Example 3 :
23+ Input : s = "0"
24+ Output : 0
25+ Explanation : There is no character that is mapped to a number starting with '0' .
26+ We cannot ignore a zero when we face it while decoding . So , each '0' should be part of "10" - - > 'J' or "20" - - > 'T' .
27+
28+ Example 4 :
29+ Input : s = "1"
30+ Output : 1
31+
32+ Constraints :
33+
34+ 1 <= s .length <= 100
35+ s contains only digits and may contain leading zero (s ).
36+
37+
38+
39+
40+ # O(n) Time and O(n) Space
41+ class Solution :
42+ def numDecodings (self , s : str ) - > int :
43+
44+ dp = [0 for i in range (len (s )+ 1 )]
45+ dp [0 ] = 1
46+ dp [1 ] = 0 if s [0 ]== '0' else 1
47+
48+ for i in range (2 , len (s )+ 1 ):
49+
50+ one_digit = s [i - 1 :i ]
51+ two_digits = s [i - 2 :i ]
52+
53+ if int (one_digit ) >= 1 :
54+ dp [i ] += dp [i - 1 ]
55+
56+ if 10 <= int (two_digits ) <= 26 :
57+ dp [i ] += dp [i - 2 ]
58+
59+
60+ return dp [- 1 ]
You can’t perform that action at this time.
0 commit comments