设计一个算法,可以在字符串中找到最长的回文子串。
最长回文子串算法
算法思想
- 从字符串中的每个字符开始,以该字符为中心向两边扩展,寻找回文子串
- 以每个字符为中心,分别处理奇数长度和偶数长度的回文串
算法步骤
- 遍历字符串,以每个字符为中心寻找奇数长度的回文子串
- 遍历字符串,以每对相邻字符为中心寻找偶数长度的回文子串
- 记录并返回找到的最长的回文子串
示例:
输入:"babad" 输出:"bab" 或 "aba"
Python代码示例
# 定义函数实现最长回文子串的查找
def longest_palindrome(s: str) -> str:
res = ""
for i in range(len(s)):
odd = find_palindrome(s, i, i)
even = find_palindrome(s, i, i+1)
res = max(res, odd, even, key=len)
return res
# 辅助函数,以left和right为中心寻找回文子串
def find_palindrome(s: str, left: int, right: int) -> str:
while left >= 0 and right < len(s) and s[left] == s[right]:
left -= 1
right += 1
return s[left+1:right]