Skip to content

Commit 300301b

Browse files
Oct 2nd : Decode ways
1 parent ad271c0 commit 300301b

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

Python/decodeWays.py

+46
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
"""
2+
Leetcode 91. Decode ways
3+
Method used : Memoization
4+
"""
5+
6+
7+
def check(s,mp): # Checks if the string is a valid number in the map of numbers
8+
return int(s in mp.keys())
9+
g_d = dict()
10+
class Solution():
11+
def helper(self,s,mp):
12+
if(s in g_d):
13+
return g_d[s]
14+
if(s[0] == '0'): # if the string starts with 0, you cannot decode
15+
return 0
16+
if(len(s) == 2): # len(s) == 2; two cases : checking two characters(s[0] && s[1]) seperately and the s[0:2]
17+
return check(s[0:2],mp) + self.helper(s[1:],mp)
18+
if(len(s) == 1 ):
19+
return int(s in mp.keys())
20+
"""
21+
There are two cases
22+
* Pick one character from the front
23+
* Check if the charcater chosen is valid
24+
* Pick two character from the front
25+
* Check if the charcater chosen is valid
26+
the conditions below help to validate the conditions mentioned here.
27+
"""
28+
if not check(s[0:2],mp) and check(s[0:1],mp):
29+
g_d[s] = self.helper(s[1:],mp)
30+
return g_d[s]
31+
if not check(s[0:1],mp) and check(s[0:2],mp):
32+
g_d[s] = self.helper(s[2:],mp)
33+
return g_d[s]
34+
g_d[s] = self.helper(s[1:],mp) + self.helper(s[2:],mp)
35+
36+
return g_d[s]
37+
def numDecodings(self, s):
38+
"""
39+
:type s: str
40+
:rtype: int
41+
"""
42+
mp = dict()
43+
for i in range(1,27):
44+
mp[str(i)] = chr(64+i)
45+
# print(mp)
46+
return self.helper(s,mp)

0 commit comments

Comments
 (0)