0
点赞
收藏
分享

微信扫一扫

leetcode (力扣) 17. 电话号码的字母组合 (队列)


题目在这:​​https://leetcode-cn.com/problems/letter-combinations-of-a-phone-number/​​

思路分析:

就是逐个组合匹配。比如输入 234 即拿2里的字母去3里匹配,然后组成一个新的字母串再拿去4里匹配即可。
使用队列进行组合。
例如:
2 : abc
3 :def
4:ghi

  • 首先将2中的字母推入队列res中,此时res中的值为 abc。假如该队列 右进左出。
  • 记录此时队列的长度为s。 (s=3)
  • 此时弹出队列中第一个字符,拿去匹配3号对应的字母串,每次匹配一个都加入到队列中。
  • 匹配1次后队列res中的值为: b c ad ae af
  • 再次进行第二次和第三次匹配,匹配过后res中的值为 ad ae af bd be bf cd ce cf.。匹配了s次。
  • 再次记录此时的队列长度为s (s=9).
  • 继续拿队列中的所有字母去匹配4号对应的字母。匹配次数 s(s = 9)次。
  • 最后队列中的值就是我们要的答案

完整代码

class Solution:
def letterCombinations(self, digits: str) -> List[str]:
d = [" ","*","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"]
res = []
if len(digits) == 0:
return res

for j in d[int(digits[0])]:
res.append(j) # 将当前的值加入队列
for i in range(len(digits)-1):
length = len(res) # 记录当前队列长度
for _ in range(length):
temp = res.pop(0)
for k in d[int(digits[i+1])]: # 遍历下一个字符串的值
res.append(temp+k)
return


举报

相关推荐

0 条评论