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

Python最长回文串代码异常:返回未触发逻辑的结果求助

问题分析与修复

核心原因

Python中列表是可变对象,直接赋值(longest_palindrome = current)传递的是内存引用,而非创建新列表。后续对current的修改会直接同步到longest_palindrome,哪怕修改发生在回文判断的逻辑之外。

具体执行流程(以输入"babad"为例)

  1. 外层循环处理第一个字符'b'(索引0),current初始化为['b']。
  2. 内层循环遍历s[idx+1:]即"abad":
    • 追加'a' → ['b','a'],不是回文,无赋值操作。
    • 追加'b' → ['b','a','b'],是回文,触发print并执行longest_palindrome = current,此时两者指向同一个列表。
    • 继续追加'a' → current变为['b','a','b','a'],由于longest_palindrome和current共享内存,它也同步变成这个值,但此时current不是回文,不会触发print。
    • 最后追加'd' → current变为['b','a','b','a','d'],同样不触发回文判断,但longest_palindrome已经被之前的修改污染。

修复代码

只需要在赋值时创建列表副本,避免引用传递的问题:

def longestPalindrome(s: str) -> str:
    aux = 0 
    while True:
        if s[-(aux+1)] not in s[:-(aux+1)]:
            aux+=1
        else:
            break
    s = s if aux == 0 else s[:len(s)-aux]
    
    longest_palindrome= []
    for idx, value in enumerate(s):
            current = [value]
            if value not in s[idx+1:]:
                continue
            for v in (s[idx+1:]):
                 current.append(v)
                 if current == list(reversed(current)):
                     print('if logic current=', current)
                     # 改为创建副本,避免引用同步修改
                     longest_palindrome = current.copy() if len(longest_palindrome) < len(current) else longest_palindrome
    return longest_palindrome
                     
res = longestPalindrome("babad")
print('result:', res)

修复后输出

if logic current= ['b', 'a', 'b']
if logic current= ['a', 'b', 'a']
result: ['a', 'b', 'a']

(注:由于两个回文长度相同,最终返回哪一个取决于遍历顺序,这里返回的是第二个出现的最长回文)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 20:12:45