5. Longest Palindromic Substring
最長回問子串
本題來自LeetCode OJ
題目翻譯
Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
給定一個字符串s,找出s中的最長迴文子串。你可以假定s的最大長度爲1000。
例1:
Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.
例2:
Input: "cbbd"
Output: "bb"
題目分析
迴文的特點就是正着和反着是相同的,或者說是鏡面的。所以用sr表示倒敘後的s字符串,如果他是迴文子串的一個充要條件就是它存在sr中且本身爲迴文。
代碼示例
class Solution(object):
def longestPalindrome(self, s):
"""
:type s: str
:type sr: str
:rtype: str
"""
sr = "".join(reversed(s)) # sr爲s的倒序
answerLen = 1 # 最短的迴文子串即爲一個字符
try:
answer = s[0] # 取第一個字符作爲默認迴文
except:
return None
i = 0
# 因爲最後一個字符肯定不需要去判斷
while i < len(s) - 1:
plus = 2
# plus-1爲迴文的字符串的現有長度,致所有加plus<=len(s)的判斷條件是由於避免出現s本身爲迴文
while sr.find(s[i:i+plus]) != -1 and plus <= len(s)-i:
plus = plus + 1
if plus-1 > answerLen:
taskAnswer = s[i:i+plus-1]
# 這時候需要判斷備選的答案本身是否爲迴文
if taskAnswer == taskAnswer[::-1]:
answer = taskAnswer
answerLen = len(answer)
i = i + 1
return answer