Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring.
class Solution:
# @param {string} s input string
# @return {string} the longest palindromic substring
def longestPalindrome(self, s):
if s == None or len(s) == 1:
return s
# Write your code here
result = ''
for i in range(len(s)):
left, right = i, i + 1
while left >= 0 and right < len(s) and s[left] == s[right]:
if right - left + 1 > len(result):
result = s[left: right + 1]
left -= 1
right += 1
left, right = i - 1, i + 1
while left >= 0 and right < len(s) and s[left] == s[right]:
if right - left + 1 > len(result):
result = s[left: right + 1]
left -= 1
right += 1
return result
class Solution:
# @param {string} s input string
# @return {string} the longest palindromic substring
def longestPalindrome(self, s):
# Write your code here
n = len(s)
longest = ''
isPalin = [[False for y in range(n)] for x in range(n)]
# i + 1 > j -1 说明从i到j只有一个或者两个元素的时候,不需要进行isPalin[i][j] 判断。
# 如果不进行i + 1> j- 1的判定,也可以初始化,i到j的一个到两个元素。
for i in range(n - 1, -1, -1):
for j in range(i, n):
if (i + 1 > j - 1 or isPalin[i + 1][j - 1]) and s[i] == s[j]:
isPalin[i][j] = True
if len(s[i: j + 1]) > len(longest):
longest = s[i: j + 1]
return longest