原题
Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
Example 1:
Input: “babad”
Output: “bab”
Note: “aba” is also a valid answer.
Example 2:
Input: “cbbd”
Output: “bb”
解法
参考: Python easy to understand solution with comments (from middle to two ends).
遍历字符串, 寻找在i 点时能构成的最长回文, 回文有两种情况: 1) 奇数长度, 如’aba’. 2) 偶数长度, 如’abba’, 每次遍历时更新res.
Time: O(n)
Space: O(1)
代码
class Solution(object):
def longestPalindrome(self, s):
"""
:type s: str
:rtype: str
"""
def getPalindrome(s, l, r):
while l >= 0 and r < len(s) and s[l] == s[r]:
l -= 1
r += 1
return s[l+1:r]
res = ''
for i in range(len(s)):
# odd case, like 'aba'
sub = getPalindrome(s, i, i)
if len(sub) > len(res):
res = sub
# even case, like 'abba'
sub = getPalindrome(s, i, i+1)
if len(sub) > len(res):
res = sub
return res
本文介绍了一种在给定字符串中寻找最长回文子串的有效算法,通过从中间向两端扩展的方式,处理奇数和偶数长度的回文情况,实现时间复杂度为O(n)的解决方案。
589

被折叠的 条评论
为什么被折叠?



