【问题标题】:UnboundLocalError Leetcode #5. Longest Palindromic SubstringUnboundLocalError 力扣#5。最长回文子串
【发布时间】:2023-01-11 23:55:53
【问题描述】:

Leetcode 一直给我这个 UnboundLocalError,我不知道为什么......

这是我的代码

class Solution:
    def longestPalindrome(self, s: str) -> str:
        def isPalindrome(s):
            if len(s) == 1:
                return True
            if len(s) == 2 and s[0] == s[1]:
                return True
            else:
                if s[0] == s[-1]:
                    return isPalindrome(s[1:-1])
                else:
                    return False
        max_ = 0
        lenght = len(s)
        for i in range(lenght):
            for r in range(i + 1, lenght):
                if isPalindrome(s[i:r]):
                    len_ = r - i + 1
                    if len_ > max_:
                        max_ = len_
                        final = s[i:r]
        return final

它给我的错误是

UnboundLocalError: local variable 'final' referenced before assignment
    return final

有人可以帮我理解为什么会这样吗? 先感谢您

我认为在最终字符串为 len() = 1 的情况下可能会出现问题。在这种情况下,s[i : r] 可能是个问题

【问题讨论】:

    标签: python python-3.x debugging unbound


    【解决方案1】:

    您的 final 变量在 if 块内定义,在外部不可见。只需在外面声明即可摆脱此错误

    class Solution:
        def longestPalindrome(self, s: str) -> str:
            def isPalindrome(s):
                if len(s) == 1:
                    return True
                if len(s) == 2 and s[0] == s[1]:
                    return True
                else:
                    if s[0] == s[-1]:
                        return isPalindrome(s[1:-1])
                    else:
                        return False
            max_ = 0
            lenght = len(s)
    
            final = 0 # declared final here
    
            for i in range(lenght):
                for r in range(i + 1, lenght):
                    if isPalindrome(s[i:r]):
                        len_ = r - i + 1
                        if len_ > max_:
                            max_ = len_
                            final = s[i:r]
          
    
            return final
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-15
      • 1970-01-01
      • 2015-07-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多