17. Letter Combinations of a Phone Number-python

本文介绍了一种解决电话号码字母组合问题的算法实现。利用队列思想,通过遍历输入数字并根据数字到字母的映射关系生成所有可能的字母组合。文中详细解释了算法流程,包括初始化队列、遍历数字、出队与组合操作等关键步骤。

开发板推荐:天空星STM32F407VET6开发板

超高性价比 STM32主控 | 超高主频 | 一板兼容百芯 | 比赛神器 | 沉金彩色丝印

Leetcode上对deque不支持,所以用list和游标模拟队列,应为这个题目是队列的经典应用。

原题

Given a digit string, return all possible letter combinations that the number could represent.

A mapping of digit to letters (just like on the telephone buttons) is given below.

这里写图片描述

Example1:

Input:Digit string “23”
Output: [“ad”, “ae”, “af”, “bd”, “be”, “bf”, “cd”, “ce”, “cf”].

Example1:

Input: “12”
Output: “1a” “1b” “1c”

思路

  1. 队列初始化,并放入一个空字符
  2. 遍历输入的字符串数字
  3. 对当前数字,如果队列头元素长度等于数字索引,则出队,遍历这个数字对应的字符集合,并且与队列的头元素组合;
  4. 不断出队,直到列头元素长度不等于数字索引。

Code

class Solution(object):
    def letterCombinations(self, digits):
        """
        :type digits: str
        :rtype: List[str]
        """
        digits = digits.strip()
        if len(digits)==0:
            return []
        rtn_queue=[""]
        head_ind=0  # the head of queue
        head_ele="" # the head element of queue
        mapping= ["0", "1", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"]
        dig_ind=0
        for dig in digits:            
            x = int(dig)
            while len(rtn_queue[head_ind])==dig_ind:
                head_ele=rtn_queue[head_ind]
                head_ind+=1
                for ch in mapping[x]:
                    rtn_queue.append(head_ele+ch)
            dig_ind+=1
        queue_n = len(rtn_queue)
        return rtn_queue[head_ind:queue_n]

开发板推荐:天空星STM32F407VET6开发板

超高性价比 STM32主控 | 超高主频 | 一板兼容百芯 | 比赛神器 | 沉金彩色丝印

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值