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”
思路
- 队列初始化,并放入一个空字符
- 遍历输入的字符串数字
- 对当前数字,如果队列头元素长度等于数字索引,则出队,遍历这个数字对应的字符集合,并且与队列的头元素组合;
- 不断出队,直到列头元素长度不等于数字索引。
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]