Leetcode:(Python)(String) Letter Combinations of a Phone Number

許博淳
數據共筆
Published in
May 1, 2023

題目連結:https://leetcode.com/problems/letter-combinations-of-a-phone-number/description/

題意說明:

傳統的電話案件會對應英文字母,給定一段數字,輸出所有有可能的字母組合

初始想法

參考他人解法:https://leetcode.com/problems/letter-combinations-of-a-phone-number/solutions/3386950/straight-forward-python-solution/?orderBy=hot&languageTags=python3

  • 用第一層迴圈找出每一個 digits的數字
  • 用第二層迴圈把數字對應的英文字母展開
  • 用第三層迴圈把展開的英文字母和先前建立好的組合做 mapping

看似很直覺很爛的作法,執行速度基本上已經最佳 . . .

第三層該怎麼做我一開始想不透,所以參考了別人的作法

Code

number_to_alphabet ={
'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']
}

class Solution:
def letterCombinations(self, digits: str) -> List[str]:
if not digits:
return []

output = [""]
for d in digits:
temp = []

for alphabet in number_to_alphabet[d]:
for combination in output:
temp.append(combination+alphabet)

output = temp
return output

--

--