给定一个字符串 s,找到 s 中最长的回文子串。你可以假设 s 的最大长度为 1000。
示例 1:
输入: \"babad\" 输出: \"bab\" 注意: \"aba\" 也是一个有效答案。
示例 2:
输入: \"cbbd\" 输出: \"bb\"
class Solution:
def longestPalindrome(self, s):
\"\"\"
:type s: str
:rtype: str
\"\"\"
#最长回文串必然在最长公共子串中,从第一个字符开始,判断其是否为会问字符串
length = len(s)
result = \"\"
if length == 0 or length == 1:
return s
for i in range(length):
string = self.issub(s, i, length)
if len(string) > len(result):
result = string
return result
def issub(self, s, i, length):
j = 0
string1 = \"\"
string2 = \"\"
while(i - j >= 0 and i + j < length): ##回文串为奇数个
if s[i - j] != s[i + j]:
break
else:
j += 1
if j != 0:
string1 = s[i - j + 1 : i + j]
else:
string1 = s[i]
k = 0
while(i - k >= 0 and i + k + 1< length): ##回文串为偶数个
if s[i - k] != s[i + k + 1]:
break
else:
k += 1
if k != 0:
string2 = s[i - k + 1 : i + k + 1]
if len(string1) > len(string2):
string = string1
else:
string = string2
return string
继续阅读与本文标签相同的文章
下一篇 :
倪光南院士:华为市值13000亿美金
-
运营专家详解“花呗分期”
2026-05-18栏目: 教程
-
谈一谈 iOS 的锁
2026-05-18栏目: 教程
-
《Android自定义控件开发入门与实战》| 每日读本书
2026-05-18栏目: 教程
-
除了吃月饼,中秋节还能干啥? | 9月12号栖夜读
2026-05-18栏目: 教程
-
图数据库爱好者的聚会在谈论什么?
2026-05-18栏目: 教程
