Leetcode 第 17 题索引超出范围错误

问题描述 投票:0回答:1

任何人都可以告诉我为什么我在下面的代码中收到IndexError。这对我来说没有任何意义。

class Solution(object):
    def letterCombinations(self, digits):
        matchnums={
        "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"]
        }
        res = []
        temp = matchnums[digits[0]]
        if digits=="":
            return res
        elif len(digits)==1:
            return matchnums[digits]
        else:
            for k in range(1,len(digits)):
                res=[]
                for i in range(len(temp)):
                    for j in range(len(matchnums[digits[k]])):
                        res.append(temp[i]+matchnums[digits[k]][j])
                temp=res
        return res

错误在

temp = matchnums[digits[0]]

线。我做错了什么?

python python-3.x string dictionary
1个回答
0
投票

由于数字可能是空字符串,因此您需要提前检查。 移动

if digits=="":
    return res

之前

temp = matchnums[digits[0]]
© www.soinside.com 2019 - 2024. All rights reserved.