Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
Example 1:
Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.
Example 2:
Input: "cbbd"
Output: "bb"
首先,我想到的暴力搜索,把所有的子串全都找出来,然后一个一个判断是不是回文串,判断回文串很简单,只需要从两端开始检查字符是不是一样就够了。这个算法的时间复杂度是n的三次方,结果时间没过....
class Solution:
def longestPalindrome(self, s: 'str') -> 'str':
res = ""
maxlen = 0
if len(s) == 1:
return s
for i in range(0, len(s)):
for j in range(i, len(s)):
isPalindromic = self.check(s[i : j + 1])
if isPalindromic:
if j - i + 1 > maxlen:
maxlen = j - i + 1
res = s[i: j + 1]
return res
def check(self, s: 'str') -> 'bool':
i = 0
j = len(s) - 1
while i <= j:
if s[i] != s[j]:
return False
elif s[i] == s[j]:
i += 1
j -= 1
return True
接下来,就要换一个思路,在网上找的是可以用动态规划来做,动态规划,我还是没想明白,先把记忆化搜索的算法写出来了,感觉这个比较好理解,大致就是建立一个二维的矩阵,算法的时间复杂度就是n方,然后进行判断从i到j是否是一个回文串可以利用i+1到j-1是否是一个回文串进行判断,从而加快算法运行速度,代码如下
class Solution:
def longestPalindrome(self, s: 'str') -> 'str':
if len(s) == 0 or len(s) == 1:
return s
# when len(s) >= 1, make sure the return has a value
maxlen = 1
res = s[0]
# initialize the memory matrix
memo = [ [False for i in range(len(s))] for j in range(len(s))]
for i in range(0, len(s)):
memo[i][i] = True
# fill the memory matrix by judging the whether substring [i,,,,,j] is a Palindrome
# actually, we just fill the half of the matrix because we need j >= i
for j in range(1, len(s)):
for i in range(j - 1, -1, -1):
if s[i] != s[j]:
memo[i][j] = False
elif i + 1 == j and s[i] == s[j]:
memo[i][j] = True
if j - i + 1 > maxlen:
maxlen = j - i + 1
res = s[i: j + 1]
elif i + 1 < j and s[i] == s[j]:
memo[i][j] = memo[i+1][j-1]
if memo[i][j] == True and j - i + 1 > maxlen:
maxlen = j - i + 1
res = s[i: j + 1]
return res
最后看了下之前学过的数据结构与算法的知识,用动态规划重新写,其实和记忆化搜索差不多的
class Solution:
def longestPalindrome(self, s: 'str') -> 'str':
if len(s) == 0 or len(s) == 1:
return s
# when len(s) >= 1, make sure the return has a value
maxlen = 1
res = s[0]
# initialize the memory matrix
memo = [ [False for i in range(len(s))] for j in range(len(s))]
for i in range(len(s)):
memo[i][i] = True
# fill the memory matrix by judging the whether substring [i,,,,,j] is a Palindrome
# actually, we just fill the half of the matrix because we need j >= i
for j in range(0, len(s)):
for i in range(j):
if i == j:
memo[i][j] = True
elif s[i] != s[j]:
memo[i][j] = False
elif i < j and s[i] == s[j]:
# state transition equation
memo[i][j] = (i+1 == j) or memo[i+1][j-1]
if j - i + 1 > maxlen and memo[i][j] == True:
maxlen = j - i + 1
res = s[i:j+1]
return res