Leetcode-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, and there exists one unique longest palindromic substring.
思路:从头开始遍历整个字符串。然后以每个字符串为中点向两边扩展,直到最长的Palindromic,记录中间出现的Palindromic的最大长度。需要注意的是Palindromic的长度可能为奇数也可能为偶数。
时间复杂度:O(n^2)
空间复杂度:O(1)
Show the code:
Run Time: 1247 ms
class Solution:
# @return a string
def longestPalindrome(self, s):
length = len(s)
def expand(left, right):
while left >= 0 and right < length and s[left] == s[right]:
left -=1
right +=1
return right - left -1
start, end = 0, 0
for i in range(length):
len1 = expand(i,i)
len2 = expand(i,i+1)
Len = max (len1, len2)
if end - start < Len:
start = i - (Len-1)/2
end = i + Len/2
return s[start:end+1]