LeetCode Medium:5. Longest Palindromic Substring
一、题目
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"
题目的意思是找最大的回文串,回文串有两种:一种是中间无重复的,如“aba”,一种是中间是重复的。比如“xaaaaax”
二、思路
我能想到的是暴力解法,将每一个字符都作为回文字符串中心,依次扩展,但是这种算法复杂度很高,如代码longestPalindrome0,而且我没有考虑到中间带重复的,所以没有编译通过,在网上看大神的博客,
找了两种比较好的做法,代码longestPalindrome1和代码longestPalindrome2,将中间重复的作为一个整体考虑。
三、代码
#coding:utf-8
def longestPalindrome0(s):
"""
:type s: str
:rtype: str
"""
'''
maxcount = 0
for i in range(1,len(s)-1):
count = 0
j = 1
curleft = i - j
curright = i + j
while s[curleft] == s[curright]:
j+=1
count+=1
curleft-=1
curright+=1
if curleft < 0 or curright > len(s) - 1:
print('break')
break
if maxcount < count:
maxcount = count
a = curleft + 1
b = curright
res = s[a:b:1]
print(maxcount)
print(res)
return maxcount,res
'''
'https://www.cnblogs.com/chruny/p/4791078.html'
def longestPalindrome1(s):
"""
:type s: str
:rtype: str
"""
size = len(s)
if size == 1:
print(s)
return s
if size == 2:
if s[0] == s[1]:
print(s)
return s
print(s[0])
return s[0]
maxp = 1
ans = s[0]
i = 0
while i < size:
j = i + 1
while j < size:
if s[i] == s[j]:
j += 1
else:
break
k = 0
while i - k - 1 >= 0 and j + k <= size - 1:
if s[i - k - 1] != s[j + k]:
break
k += 1
if j - i + 2 * k > maxp:
maxp = j - i + 2 * k
ans = s[i - k:j + k]
if j + k == size - 1:
break
i = j
print(ans)
return ans
'https://blog.csdn.net/shiroh_ms08/article/details/26094141'
def longestPalindrome3(s):
if not s or len(s) == 1:
return s
# record the result value
max_length = 1
start_index = 0
end_index = 0
for i in range(0, len(s)-1):
count = 1
# aba
if s[i] != s[i+1]:
while i-count >= 0 and i + count < len(s) and s[i-count] == s[i+count]:
count += 1
if (count-1) * 2 + 1 > max_length:
max_length = (count-1) * 2 + 1
start_index = i - count + 1
end_index = i + count - 1
# xaaaaax
else:
count_repeat = 1
count = 0
while i+1 < len(s) and s[i] == s[i+1]:
i += 1
count_repeat += 1
while i-count_repeat+1-count >= 0 and i + count < len(s) and s[i-count_repeat+1-count] == s[i+count]:
count += 1
if (count-1) * 2 + count_repeat > max_length:
max_length = (count-1) * 2 + count_repeat
start_index = i - count -count_repeat + 2
end_index = i + count - 1
print(s[start_index:end_index+1])
return s[start_index:end_index+1]
if __name__ == '__main__':
s1 = 'dabbac'
#longestPalindrome1(s1)
s3 ='axaaaaax'
longestPalindrome3(s3)
参考博客:
https://blog.csdn.net/shiroh_ms08/article/details/26094141
https://www.cnblogs.com/chruny/p/4791078.html
既然无论如何时间都会过去,为什么不选择做些有意义的事情呢
浙公网安备 33010602011771号