今天做一道最长回文子串问题

Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.

给定字符串s,找到其最长回文子串并输出

回文定义为:字符串s与s的反转s`完全相等

Example:

Input: "babad"

Output: "bab"

Note: "aba" is also a valid answer.

Example:

Input: "cbbd"

Output: "bb"

思路一:
找到所有子串后,在判断子串是否回文,但是看题目说字符长度为1000,这样的暴力解法的时间复杂度为o(n^3),附上暴力解法的代码,但是会提示 Time Limit Exceeded

 1 class Solution(object):
 2     def longestPalindrome(self, s):
 3         """
 4         :type s: str
 5         :rtype: str
 6         """
 7         Str = ''
 8         Max = 0
 9         for length in range(1,len(s)+1):
10             for i in range(len(s)-length+1):
11                 j = i+length
12                 if(self.reversedStr(s[i:j])):
13                     if(Max<length):
14                         Max = length
15                         Str = s[i:j]
16           
17         return Str
18     def reversedStr(self,s):
19         for i in range(len(s)):
20             if(s[i] != s[len(s)-i-1]):
21                 return False
22         return True

思路二:
动态规划解法
时间复杂度为o(n^2)
具体算法如下:
首先我们假设有字符串s,子串为s`,start为子串s`在s上的初始位置,end为子串s`在s上的结束位置
我们假设s[start:end]回文子串,那么s[start+1,end-1]必定也是回文子串就会存在公式.
因此我们用dp[start][end] = dp[start+1][end-1] and (s[start]与s[end]是否相等)
如果子串dp[start+1][end-1]为回文子串并且s[start]==s[end]的时候,说明dp[start][end]也是回文子串
而s中的单个字符与本身相等的,所以dp[i][i]也是回文子串
如果s[i]==s[i+1],dp[i][i+1]也是回文字串
因此我们的代码如下所示:

 1 class Solution(object):
 2     def longestPalindrome(self, s):
 3         """
 4         :type s: str
 5         :rtype: str
 6         """
 7         start = 0
 8         MaxLength = 0
 9         dp = [[False for i in range(len(s))] for i in range(len(s))]
10         if(len(s)==1):
11             return s
12         for i in range(len(s)):
13             dp[i][i] = True
14             if(i<len(s)-1 and s[i] == s[i+1]):
15                 dp[i][i+1] = True
16                 start = i
17                 MaxLength = 2
18         for length in range(3,len(s)+1):
19             for i in range(len(s)-length+1):
20                 j = i+length-1
21                 if(s[j]==s[i] and dp[i+1][j-1]):
22                     dp[i][j] = True
23                     MaxLength = length
24                     start = i
25         if(MaxLength>=2):
26             return s[start:start+MaxLength]
27         return s[0]

还有其他解法,比方说用某个字符为中心点往四周拓展看是否回文,时间复杂度为o(n^2),说还有一个(Manacher’s algorithm)时间复杂的o(n),还需要再看看






posted on 2018-01-22 14:44  Qarnet  阅读(92)  评论(0)    收藏  举报