题目:
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"
思考:
本题主要出现的重文情况有两种:1、个数为奇数,关于中间一个字符两边对称;2、个数为偶数,整个字符串两边对称。根据遍历重文的思路,从一个位置开始向两边遍历,看是否两边的字符相等,去找整个重文的长度。因此除了要遍历每一个字符的两边意外,还要遍历两个字符中间位置的两边 是否相等,因此为了简便处理,我现在在本来字符串的基础上加入一个特殊的字符:空格;如本来是“abc”的,我处理完后就变成了“ a b c ”,这样我除了检查a b c三个字符以外,还要检查空格的两边是否相等,整个字符的长度变成了2n+1。每一个位置都去遍历两边寻找整个重文串,遇到空格跳过,当找到一个比记录的重文串要长的时候就重新记录最长的重文串,最后得出结果
代码:
class Solution(object):
def longestPalindrome(self, s):
if len(s) == 1 or len(s) == 0:
return s
newString = " "
for string in s:
newString +=string + " "
check = []
ans = s[0]
for i in range(1,len(newString)-2):
j = 0
if newString[i] == " ":
candidate = ""
else:
candidate = ""+newString[i]
while True:
j += 1
if i-j >=0 and j+i < len(newString) and (newString[i-j] == newString[i+j]):
if newString[i+j] == " ":
continue
candidate = newString[i-j] + candidate + newString[i+j]
else:
if j != 1 and j != 2:
if len(candidate) > len(ans):
ans = candidate
break
return ans
结果: