难度:Medium
描述:
Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
Example:
Input: "babad" Output: "bab" Note: "aba" is also a valid answer.
Example:
Input: "cbbd" Output: "bb"
思路:
最开始看有点蒙,想着把字符串倒过来看又没什么方法解决,想了半小时发现确实没有用处。
如果从回文字串的边缘看不出解决方法,那只好从中心来解决
回文字串有两种对称模式,偶数的中间是AA这样的,奇数的是ABA这样的,通过找到这两种最小的模式,然后不断扩大,AA->CAAC->DCAACD,这样就能找到最大的回文串。
当然会有一些特殊情况,比如只有1个字符的,有两个字符且都不同,整个数组没有字符数大于等于2的,都返回第一个字符
具体看代码:
class Solution(object):
def longestPalindrome(self, s):
length = len(s)
longest = ""
if len(s) == 1:
return s
if len(s) == 2 and s[0] != s[1]:
return s[0]
for x in range(length-1):
b = x
e = x+1
if(s[b] == s[e]):
while (b >= 0 and e < length) and (s[b] == s[e]):
b = b-1
e = e+1
if len(s[b+1:e]) > len(longest):
longest = s[b+1:e]
for x in range(length-2):
b = x
m = x+1
e = x+2
if (s[b] == s[e]):
while (b >= 0 and e < length) and (s[b] == s[e]):
b = b-1
e = e+1
if len(s[b+1:e]) > len(longest):
longest = s[b+1:e]
if len(longest) == 0:
return s[0]
return longest
本文介绍了一种寻找字符串中最长回文子串的有效算法。通过从中心向外扩展的方法,该算法能处理奇数和偶数长度的回文串,适用于多种情况。
972

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



