給定乙個字串 s,找到 s 中最長的回文子串。你可以假設 s 的最大長度為 1000。
示例 1:
輸入:"babad"
輸出:"bab"
注意:"aba" 也是乙個有效答案。
示例 2:
輸入:"cbbd"
輸出:"bb"
方案一: 超時
class
solution
:def
longestpalindrome
(self, s:
str)
->
str:
newtarget =
max_len =
len(s)-1
iflen
(s)==0or
len(s)==1
:return s
while max_len:
for i in
range
(len
(s))
:if i+max_len >
len(s)-1
:continue
target = s[i:i+max_len+1]
newtarget =
list
(target)
if newtarget == newtarget[::
-1]:
return target
max_len = max_len -
1return s[
0]
方案二:
s ="babad"
res = s[0]
for i in
range
(len
(s))
:for j in
range
(i +1,
len(s)):
if s[i]
== s[j]
:if s[i:j+1]
== s[i:j+1]
[::-
1]: res = s[i:j+1]
if(len(s[i:j+1]
)>=
len(res)
)else res
print
(res)
方案三:中心擴充套件法
中心擴充套件就是把給定的字串的每乙個字母當做中心,向兩邊擴充套件,這樣來找最長的子回文串。演算法複雜度為o(n^2)。
需要考慮兩種情況:
長度為奇數的回文串,比如a, aba, abcba
長度為偶數的回文串,比如aa, abba
#!/usr/bin/python
# -*- coding: utf-8 -*-
defmax_substr
(string)
: s_list =
[s for s in string]
string =
'#'+
'#'.join(s_list)
+'#'
max_length =
0 length =
len(string)
for index in
range(0
, length)
: r_length = get_length(string, index)
if max_length < r_length:
max_length = r_length
return max_length
defget_length
(string, index)
:# 迴圈求出index為中心的最長回文字串
length =
0 r_ =
len(string)
for i in
range(1
,index+1)
:if index+i < r_ and string[index-i]
== string[index+i]
: length +=
1else
:break
return length
if __name__ ==
"__main__"
: result = max_substr(
"35534321"
)print result
最長回文子串 LeetCode 五 最長回文子串
題目 最長回文子串 給定乙個字串s,找到s中最長的回文子串。你可以假設s的最大長度為 1000。題目解析 回文?當回文串長度為奇數時,比如 北京計程車租出京北 當回文串長度為偶數的時候,比如 1221 以上兩種情況有乙個共同的特點就是有乙個中心,那在 中如何表示中心呢?class solution ...
leetcode 最長回文子串
給定乙個字串 s,找到 s 中最長的回文子串。你可以假設 s 的最大長度為1000。示例 1 輸入 babad 輸出 bab 注意 aba 也是乙個有效答案。示例 2 輸入 cbbd 輸出 bb 中心拓展法 由乙個中心點開始向兩邊拓展,檢測邊界,判斷兩個值是否相等,相等則繼續拓展下去,檢測邊界。1....
最長回文子串(LeetCode)
給定乙個字串s,找到s中最長的回文子串。你可以假設s的最大長度為 1000。示例 1 輸入 babad 輸出 bab 注意 aba 也是乙個有效答案。示例 2 輸入 cbbd 輸出 bb class solution def longestpalindrome self,s type s str r...