17_Letter Combinations of a Phone number
Last updated
Last updated
Input: "23"
Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].def letterCombinations(digits):
"""
:type digits: str
:rtype: List[str]
"""
if digits == "": return []
# mapping from digits to letters
map = ["abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"]
# iterative approach
# first pass to compute the length of final output
n = 1
for i in range(len(digits)):
letters = map[int(digits[i])-2]
n *= len(letters)
out = [""]*n
index = range(n)
length = n
# second pass to append letter
for i in range(len(digits)):
letters = map[int(digits[i])-2]
length /= len(letters)
for j in range(n):
out[j] += letters[index[j]//length]
index[j] %= length
return out