Last active
December 29, 2020 18:17
-
-
Save subsr97/2a82bc10b74712d070d6d0ce550813a2 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution: | |
num_to_alpha_dict = {str(num): chr( ord("A") + num-1 ) for num in range(1,27)} | |
ways = 0 | |
# Dictionary for memoization | |
ways_dict = dict() | |
def decode_message(self, s): | |
current_ways = self.ways | |
if s == "": | |
self.ways += 1 | |
return | |
if s in self.ways_dict: | |
self.ways += self.ways_dict[s] | |
return | |
if s[0] in self.num_to_alpha_dict: | |
self.decode_message(s[1:]) | |
if len(s) >= 2 and s[0:2] in self.num_to_alpha_dict: | |
self.decode_message(s[2:]) | |
if self.ways > current_ways: | |
self.ways_dict[s] = self.ways - current_ways | |
def numDecodings(self, s: str) -> int: | |
self.decode_message(s) | |
print(self.ways_dict) | |
return self.ways | |
def main(): | |
solution = Solution() | |
input_string = "12345" | |
print("Input:", input_string) | |
print("Answer:", solution.numDecodings(input_string)) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment