File tree 2 files changed +50
-21
lines changed
2 files changed +50
-21
lines changed Load Diff This file was deleted.
Original file line number Diff line number Diff line change
1
+ '''
2
+ A message containing letters from A-Z is being encoded to numbers using the
3
+ following mapping:
4
+ 'A' -> 1
5
+ 'B' -> 2
6
+ ...
7
+ 'Z' -> 26
8
+ Given a non-empty string containing only digits,
9
+ determine the total number of ways to decode it.
10
+ '''
11
+
12
+ def num_decodings (s : str ):
13
+ '''
14
+ >> num_decodings("12")
15
+ 2
16
+ >> num_decodings("226")
17
+ 3
18
+ '''
19
+ if not s or int (s [0 ]) == 0 :
20
+ return 0
21
+
22
+ last = 1
23
+ second_last = 1
24
+
25
+ for i in range (1 , len (s )):
26
+
27
+ # 0 is a special digit since it does not
28
+ # correspond to any alphabet but can be
29
+ # meaningful if preceeded by 1 or 2
30
+
31
+ if s [i ] == "0" :
32
+ if s [i - 1 ] in {"1" , "2" }:
33
+ curr = second_last
34
+ else :
35
+ return 0
36
+
37
+ elif 11 <= int (s [i - 1 :i + 1 ]) <= 26 :
38
+ curr = second_last + last
39
+ else :
40
+ curr = last
41
+
42
+ last , second_last = curr , last
43
+
44
+ return last
45
+
46
+
47
+ if __name__ == "__main__" :
48
+ import doctest
49
+
50
+ doctest .testmod ()
You can’t perform that action at this time.
0 commit comments