赞
踩
题目:原题链接(中等)
标签:动态规划、字符串
解法 | 时间复杂度 | 空间复杂度 | 执行用时 |
---|---|---|---|
Ans 1 (Python) | O ( 26 × N 2 ) O(26×N^2) O(26×N2) | O ( 26 × N 2 ) O(26×N^2) O(26×N2) | 4752ms (38.46%) |
Ans 2 (Python) | |||
Ans 3 (Python) |
解法一:
class Solution:
def longestPalindromeSubseq(self, s: str) -> int:
size = len(s)
# dp[i][j] = 令字符串[i,j]变为回文串需要删除的字符数
dp = [[[0] * 26 for _ in range(size)] for _ in range(size)]
for length in range(2, size + 1):
for i in range(size - length + 1):
j = i + length - 1
if s[i] == s[j]:
a = ord(s[i]) - 97
for k in range(26):
dp[i][j][k] = max(dp[i][j][k], dp[i + 1][j - 1][k])
if k != a:
dp[i][j][a] = max(dp[i][j][a], dp[i + 1][j - 1][k] + 1)
# print(i + 1, j - 1, k, "->", i, j, a, "=", dp[i][j][a])
# print(i, j, a, ":", dp[i][j][a])
else:
for k in range(26):
dp[i][j][k] = max(dp[i + 1][j][k], dp[i][j - 1][k])
return max(dp[0][-1]) * 2
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。