Leetcode: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"

题意:找到一个字符串的最长回文子串

思路:枚举中心位置,向两边扩展,并及时更新最长回文字串。此处回文长度是奇数和偶数分开处理。

 1 class Solution:
 2     def longestPalindrome(self,s):
 3         n = len(s)
 4         a = ''
 5         if n < 1:
 6             return 0
 7         max = 0
 8         for i in range(n):   #i记录回文串的中心
 9             j = 0
10             while (i-j >= 0) and (i+j < n):  #回文串长度为奇数
11                 if s[i-j] != s[i+j]:
12                     break
13                 c = j*2+1
14                 j += 1
15             if c > max:
16                 max = c
17                 a = s[i-j+1:i+j]
18             k = 0
19             while (i - k >= 0) and (i + k + 1 < n):  #回文串长度为偶数
20                 if s[i-k] != s[i+k+1]:
21                     break
22                 c = k*2+2
23                 k += 1
24             if c > max:
25                 max = c
26                 a = s[i - k + 1 : i + k + 1]
27         return a
28 
29 if __name__=='__main__':
30     solution=Solution()
31     print(solution.longestPalindrome('abaab'))

 

 

 

 


posted @ 2017-12-18 14:58  十二Zh  阅读(121)  评论(0)    收藏  举报