LeetCode第17题代码触发IndexError,请求解报错原因
问题原因分析
你的代码触发IndexError的核心原因是代码执行顺序错误:
- 当输入的
digits是空字符串时,你先执行了temp = matchnums[digits[0]],此时尝试访问空字符串的第0个元素,空字符串没有任何索引,直接抛出索引越界错误。 - 而你对空字符串的判断
if digits==""是在这行代码之后才执行的,根本没机会触发这个判断逻辑。
修复方案
把空字符串的判断逻辑移到所有代码的最前面,确保在访问digits的索引前先处理空输入的情况。同时可以优化部分代码逻辑,让流程更清晰:
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 = [] # 先处理空输入,避免索引访问错误 if digits=="": return res # 初始化temp为第一个数字对应的字符列表 temp = matchnums[digits[0]] if len(digits)==1: return temp else: for k in range(1,len(digits)): res=[] current_chars = matchnums[digits[k]] for i in temp: for j in current_chars: res.append(i+j) temp=res return res
额外优化说明
- 把
matchnums[digits[k]]提前赋值给current_chars,避免重复字典查找,提升代码可读性和效率。 - 遍历
temp和current_chars时直接用元素而非索引,代码更简洁直观。
内容的提问来源于stack exchange,提问作者Anurima Sengupta
相关产品推荐
相关产品推荐

