Last active
June 20, 2017 05:37
-
-
Save farkwun/ecbfde86745a09c0ff492d78c443ae88 to your computer and use it in GitHub Desktop.
17. Letter Combinations of a Phone Number - Leetcode
This file contains 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
# https://leetcode.com/problems/letter-combinations-of-a-phone-number/#/description | |
class Solution(object): | |
DIGIT_DICT = { | |
"2" : ['a', 'b', 'c'], | |
"3" : ['d', 'e', 'f'], | |
"4" : ['g', 'h', 'i'], | |
"5" : ['j', 'k', 'l'], | |
"6" : ['m', 'n', 'o'], | |
"7" : ['p', 'q', 'r', 's'], | |
"8" : ['t', 'u', 'v'], | |
"9" : ['w', 'x', 'y', 'z'] | |
} | |
def letterCombinations(self, digits): | |
""" | |
:type digits: str | |
:rtype: List[str] | |
""" | |
pointer = 0 | |
letters = "" | |
if len(digits) == 0: | |
return [] | |
else: | |
return (self.create_strings(letters, digits, pointer)) | |
def create_strings(self, letters, digits, pointer): | |
if pointer == len(digits): | |
return [letters] | |
next_chars = self.DIGIT_DICT[digits[pointer]] | |
new_strings = [] | |
for x in next_chars: | |
for s in self.create_strings(letters + x, digits, pointer + 1): | |
new_strings.append(s) | |
return new_strings | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
If leetcode accepted [""] as an answer for empty (they want [] instead of [""], then you can condense it to: