最长回文子串python_最长回文子串(Python)
給定一個(gè)字符串 s,找到 s 中最長(zhǎng)的回文子串。你可以假設(shè) s 的最大長(zhǎng)度為1000。
示例 1:
輸入: "babad"
輸出: "bab"
注意: "aba"也是一個(gè)有效答案。
示例 2:
輸入: "cbbd"
輸出: "bb"
思考這個(gè)問(wèn)題第一是從List兩邊考慮,先找到兩個(gè)相同的點(diǎn), 然后各像中心移動(dòng)1步。這個(gè)方法被PASS的原因是遇到輸入“aaabaaaa”時(shí),兩邊同時(shí)移動(dòng)則只能返回“aaaa”
第二次從回文子串的中心考慮,先假設(shè)List中每一個(gè)點(diǎn)ii都有回文子串,接下來(lái)驗(yàn)證l[ii-1]和 l[ii+1]是否相同,如果相同就繼續(xù)驗(yàn)證l[ii-2]和 l[ii+2]。對(duì)比所有結(jié)果,返回最大的子串。
class Solution:
def longestPalindrome(self, s):
""":type s: str:rtype: str"""
l=list(s)
length = len(l)
if length == 0:
return ""
if length == 1:
return s
temp=[]
result = []
i = 0
ii = 0
j = 1
flag = True
while ii < length:
i = ii - 1
j = ii + 1
while j < length and l[ii] == l[j]:
j = j + 1
temp = l[ii:j]
while (i>=0 and j<=length-1 and l[i] == l[j]):
temp = l[i:j+1]
i = i - 1
j = j + 1
if len(temp) > len(result):
result = temp
ii = ii + 1
if len(result) == 0:
return l[0]
return "".join(result)
時(shí)間復(fù)雜度是O(n^2),不知道是不是算錯(cuò)了,因?yàn)榻Y(jié)果此方法速度在最后10%中。
這里提供一個(gè)大神的O(n)解法,用到了倒敘list對(duì)比。
class Solution:
def longestPalindrome(self, s):
"""
:type s: str
:rtype: str
"""
# 如果字符串長(zhǎng)度小于2或者s等于它的倒序,則直接返回s
if len(s) < 2 or s == s[::-1]:
return s
n = len(s)
# 定義起始索引和最大回文串長(zhǎng)度,odd奇,even偶
start, maxlen = 0, 1
# 因?yàn)閕=0的話必然是不可能會(huì)有超過(guò)maxlen情況出現(xiàn),所以直接從1開(kāi)始
for i in range(1, n):
# 取i及i前面的maxlen+2個(gè)字符
odd = s[i - maxlen - 1:i + 1] # len(odd)=maxlen+2
# 取i及i前面的maxlen+1個(gè)字符
even = s[i - maxlen:i + 1] # len(even)=maxlen+1
if i - maxlen - 1 >= 0 and odd == odd[::-1]:
start = i - maxlen - 1
maxlen += 2
continue
if i - maxlen >= 0 and even == even[::-1]:
start = i - maxlen
maxlen += 1
return s[start:start + maxlen]
總結(jié)
以上是生活随笔為你收集整理的最长回文子串python_最长回文子串(Python)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: php中对象怎么访问i属性_PHP--序
- 下一篇: python3标准库书怎么样_Pytho