5 Longest Palindromic Substring
题意及示例输入如下:
Given a string s, return the longest palindromic substring in s.
Example 1:
Input: s = "babad"
Output: "bab"
Note: "aba" is also a valid answer.
Example 2:
Input: s = "cbbd"
Output: "bb"
Example 3:
Input: s = "a"
Output: "a"
Example 4:
Input: s = "ac"
Output: "a"
Constraints:
1 <= s.length <= 1000
s consist of only digits and English letters.
分析
本题有多种解法,我想到的是DP方法进行求解
也就是用空间换时间的策略。
首先,创建一个二维数组dp,这里dp[i][j]表示第i个位置的字符到第j个字符所组成的字符串是否是回文字符串。
其中字符串中每个位置上的字符都是长度为1的回文子串
所以对角元素 dp[i][i]均是true
如果字串是回文,那么dp[i][j]是true,否则为false
1. 要计算dp[i][j],我们可以先计算 dp[i+1][j-1],即去除左右两端的字符元素,剩余的部分是否是回文子串,如果剩余部分是回文子串,且去除的两端元素相等,那么dp[i][j]一定也是回文子串
当不满足上述假设,那么dp[i][j]就不是回文子串
按照这种方式,我们首先填满长度为1 2的dp数据,然后按照递推的方式算出整个dp数据的值就可以解出本题的答案。
代码如下
python solution:
class Solution:
def longestPalindrome(self, s: str) -> str:
max_L = 1
st = 0
n = len(s)
dp = [[False]*n for i in range(n)]
for i in range(n):
dp[i][i] = True
for L in range(2,n+1):
for i in range(n):
j = i+L-1
if j>=n:
break
if s[i]!=s[j]:
dp[i][j] = False
else:
if j-i<3:
dp[i][j] = True
else:
dp[i][j] = dp[i+1][j-1]
if dp[i][j] and j-i+1>max_L:
max_L = j-i+1
st = i
return s[st:st+max_L]
2021. 8.2 LC每日进步群挑战 兴趣使然