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"
思路:以每一个字母为中心,向两边寻找;或者以两个字母为中心向两边寻找。
class Solution(object):
def longestPalindrome(self, s):
"""
:type s: str
:rtype: str
"""
maxi=0
l=0
r=0
def helper(s,l,r):
while l>=0 and r<len(s) and s[l]==s[r]:
l -= 1
r += 1
length = r-l+1
return l+1,r-1,length
for i in range(len(s)):
l1, r1, length1 = helper(s,i,i)
l2, r2, length2 = helper(s,i,i+1)
if length1>maxi:
maxi = length1
l,r=l1,r1
if length2>maxi:
maxi = length2
l,r=l2,r2
return s[l:r+1]
第一次写的时候两边界线出错。 在helper写中的是while l>0.这样从第一个字母开始回文就会出错。另外l>=0时,对应最后的s[l+1,r]
还有用dp算法,比较复杂,详情参考https://blog.youkuaiyun.com/L141210113/article/details/87917988
class Solution(object):
def longestPalindrome(self, s):
if len(s)<2: return s
maxlen=0
result=''
dp = [[0]*len(s) for i in range(len(s))]
for j in range(len(s)):
for i in range(j+1):
dp[i][j] = (s[i]==s[j]) and (j-i<=2 or dp[i+1][j-1])
if dp[i][j]:
if maxlen < j-i+1:
maxlen = j-i+1
result = s[i:j+1]
return result
寻找最长回文子串

本文介绍了一种高效算法,用于在给定字符串中找到最长的回文子串。通过以每个字符为中心向两边扩展,或以两个字符为中心扩展,算法能够处理长度达1000的字符串。同时,文章对比了两种实现方式,并提供了详细的代码示例。
505

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



