1. 程式人生 > >Leetcode:5- Longest Palindromic Substring

Leetcode:5- Longest Palindromic Substring

main mes family sub long etc 擴展 input 最長

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))

Leetcode:5- Longest Palindromic Substring