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

Python新手求教:如何调用实现最长回文子串的类代码?

如何调用Python类中的方法

嘿,我来帮你搞定这个问题!Python和C++不一样,它不需要强制的main()入口函数,调用类的方法其实很简单,咱们一步步来:

核心思路:实例化类 + 调用方法

在Python里,要使用类中的方法,首先得创建这个类的实例对象,然后通过这个对象去调用对应的方法。针对你提供的LPS类,这里有两种实用的调用方式:

方式一:直接在类代码后添加调用逻辑

你可以把调用代码直接写在类定义的后面,非常直观:

class LPS:
    """
    @param s: input string
    @return: the longest palindromic substring
    """
    def longestPalindrome(self, s):
        if not s:
            return ""
        n = len(s)
        is_palindrome = [[False] * n for _ in range(n)]
        for i in range(n):
            is_palindrome[i][i] = True
        for i in range(1, n):
            is_palindrome[i][i - 1] = True
        longest, start, end = 1, 0, 0
        for length in range(1, n):
            for i in range(n - length):
                j = i + length
                is_palindrome[i][j] = s[i] == s[j] and is_palindrome[i + 1][j - 1]
                if is_palindrome[i][j] and length + 1 > longest:
                    longest = length + 1
                    start, end = i, j
        return s[start:end + 1]

# 1. 创建LPS类的实例
lps_solver = LPS()
# 2. 调用longestPalindrome方法,传入测试字符串
test_str = "babad"
result = lps_solver.longestPalindrome(test_str)
# 3. 打印结果
print(f"最长回文子串是: {result}")

方式二:用if __name__ == "__main__":包裹调用代码(推荐)

这是Python的最佳实践——当这个文件被直接运行时,调用代码才会执行;如果文件被作为模块导入到其他脚本中,这部分代码不会自动触发,避免不必要的执行:

class LPS:
    """
    @param s: input string
    @return: the longest palindromic substring
    """
    def longestPalindrome(self, s):
        if not s:
            return ""
        n = len(s)
        is_palindrome = [[False] * n for _ in range(n)]
        for i in range(n):
            is_palindrome[i][i] = True
        for i in range(1, n):
            is_palindrome[i][i - 1] = True
        longest, start, end = 1, 0, 0
        for length in range(1, n):
            for i in range(n - length):
                j = i + length
                is_palindrome[i][j] = s[i] == s[j] and is_palindrome[i + 1][j - 1]
                if is_palindrome[i][j] and length + 1 > longest:
                    longest = length + 1
                    start, end = i, j
        return s[start:end + 1]

if __name__ == "__main__":
    # 实例化类
    solver = LPS()
    # 测试多个案例
    test_cases = ["babad", "cbbd", "a", ""]
    for case in test_cases:
        palindrome = solver.longestPalindrome(case)
        print(f"输入字符串: '{case}' → 最长回文子串: '{palindrome}'")

在VS Code中的运行步骤

把代码保存为一个.py文件(比如longest_palindrome.py),然后:

  • 点击VS Code右上角的运行按钮;
  • 或者打开终端,输入python3 longest_palindrome.py(Ubuntu 18.04默认用Python3)。

这样就能看到程序输出的结果啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 08:06:34