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

LeetCode Word Break问题:本地代码正常但平台用例输出异常求助

问题原因与解决方法

核心问题1:默认参数memo={}的复用陷阱

Python函数的默认参数是定义时就创建的,不是每次调用都会新建。LeetCode会连续运行多个测试用例,前一个用例的memo字典内容会残留到下一个用例,导致后续用例读取错误的缓存值,这就是你看到本地和LeetCode结果不一致的根本原因。

核心问题2:replace截取子串的逻辑错误

你用s.replace(word, "", 1)获取匹配后的剩余字符串,但replace会替换任意位置的第一个匹配项,而非仅替换开头。比如s="abx"、word="b"时,replace会得到"ax",但题目要求的是从开头匹配后拆分,应该直接用字符串切片s[len(word):]才对。

修正后的代码

方案1:用lru_cache自动缓存(简洁版)

def wordBreak(self, s: str, wordDict: List[str]) -> bool:
    from functools import lru_cache
    word_set = set(wordDict)
    
    @lru_cache(maxsize=None)
    def dp(sub_s):
        if sub_s == "":
            return True
        # 遍历所有可能的前缀长度
        for i in range(1, len(sub_s)+1):
            prefix = sub_s[:i]
            if prefix in word_set and dp(sub_s[i:]):
                return True
        return False
    
    return dp(s)

方案2:手动管理memo(更直观)

def wordBreak(self, s: str, wordDict: List[str]) -> bool:
    word_set = set(wordDict)
    memo = {}
    
    def dp(sub_s):
        if sub_s in memo:
            return memo[sub_s]
        if sub_s == "":
            return True
        for i in range(1, len(sub_s)+1):
            prefix = sub_s[:i]
            if prefix in word_set and dp(sub_s[i:]):
                memo[sub_s] = True
                return True
        memo[sub_s] = False
        return False
    
    return dp(s)

关键修改说明

  • 移除默认参数memo={},改用函数内部创建的memo或lru_cache,确保每个测试用例的缓存独立。
  • 将wordDict转为集合,把in操作的时间复杂度从O(n)降到O(1),提升运行效率。
  • 用字符串切片sub_s[i:]替代replace,严格处理开头匹配的拆分逻辑,符合题目要求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 02:43:21