Skip to content

Latest commit

 

History

History
65 lines (63 loc) · 1.55 KB

17.md

File metadata and controls

65 lines (63 loc) · 1.55 KB

题目地址

https://leetcode-cn.com/problems/letter-combinations-of-a-phone-number/

解答1

def letterCombinations(digits):
    """ 电话号码的字母组合 """
    hashmap = {
        "2": "abc",
        "3": "def",
        "4": "ghi",
        "5": "jkl",
        "6": "mno",
        "7": "pqrs",
        "8": "tuv",
        "9": "wxyz",
    }
    list1 = []
    for i in range(len(digits) - 1, -1, -1):
        list1.append(hashmap[digits[i]])
    # 滑动窗口遍历values,每次取出两个输出结果
    if len(digits) == 1:
        return [x for x in list1[0]]
    elif not digits:
        return []
    else:
        # 取出头两个
        while list1:
            list2 = []
            list2.append(list1.pop())
            list2.append(list1.pop())
            result = []
            for i in range(len(list2) - 1, -1, -1):
                if i > 0:
                    j = i - 1
                    for k in list2[j]:
                        for l in list2[i]:
                            result.append(k + l)
                    j -= 1
            if list1:
                list1.append(result)
    return result

解答2

def letterCombinations(digits):
    """ 电话号码的字母组合 """
    if not digits:
        return []
    hashmap = {
        "2": "abc",
        "3": "def",
        "4": "ghi",
        "5": "jkl",
        "6": "mno",
        "7": "pqrs",
        "8": "tuv",
        "9": "wxyz",
    }
    result = ['']
    for d in digits:
        result = [a + b for a in result for b in hashmap[d]]
    return result