You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

LeetCode提交Python类代码报longestCommonPrefix未定义NameError问题

报错根因

你遇到的NameError: name 'longestCommonPrefix' is not defined是对Python类方法调用规则不熟悉导致的,核心问题有2个:

  • 写在Solution类里的方法属于实例方法,第一个固定参数self代表类的实例本身,类内部调用其他同属实例的方法时,必须通过self.方法名()的形式调用。你代码里递归调用longestCommonPrefix、调用辅助方法commonPrefix时都没加self.前缀,Python会把这几个调用当成查找全局作用域的独立函数,找不到自然抛错。
  • 你本地去掉类定义能正常运行,是因为那时候两个函数都定义在全局作用域,直接写函数名调用符合全局函数的调用逻辑;套入LeetCode要求的类结构后,方法的作用域从全局变成了类内部,调用规则发生了变化,原有写法就失效了。
修正方案

只需要修改类内部的方法调用写法,给所有同属类的方法调用加上self.前缀即可,一共4处修改点:

  1. 两元素分支的commonPrefix(strs)改为self.commonPrefix(strs)
  2. 递归处理左半部分的longestCommonPrefix(strs[0:idxl])改为self.longestCommonPrefix(strs[0:idxl])
  3. 递归处理右半部分的longestCommonPrefix(strs[idxl:])改为self.longestCommonPrefix(strs[idxl:])
  4. 最后合并结果的commonPrefix([left,right])改为self.commonPrefix([left,right])
修正后可直接提交的代码
class Solution:
    def longestCommonPrefix(self, strs: List[str]) -> str:
        if len(strs) == 1:
            return strs[0]
        elif len(strs) == 2:
            return self.commonPrefix(strs)
    
        idxl = len(strs) // 2
        left = self.longestCommonPrefix(strs[0:idxl])
        right = self.longestCommonPrefix(strs[idxl:])
        return self.commonPrefix([left, right])
    
    def commonPrefix(self, strs):
        min_length = min(len(strs[0]), len(strs[1]))
        for i in range(min_length):
            if strs[0][i] != strs[1][i]:
                return strs[0][0:i]
        return strs[0][0:min_length]

注:LeetCode平台运行环境已经预置了List类型的导入,提交时不需要额外写导入语句;如果要在本地运行类版本代码,需要在文件开头加上from typing import List。

内容的提问来源于stack exchange,提问作者xiaoqi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.01 23:06:28