class Solution:
def longestPalindromeSubseq(self, s: str) -> int:
n = len(s)
f = [[0]*(n+1) for _ in range(n+1)]
for i in reversed(range(n+1)):
f[i][i] =1
for j in range(i+1,n+1):
if s[i-1] == s[j-1]:
f[i][j] = f[i+1][j-1]+2
else:
f[i][j] = max(f[i+1][j],f[i][j-1])
return f[1][n]
用start 和len来Loop
class Solution:
def longestPalindromeSubseq(self, s: str) -> int:
n = len(s)
f = [[0]*(n+1) for _ in range(n+1)]
for i in range(n+1):
f[i][i] = 1
for ln in range(1,n+1):
for start in range(1,n+1-ln):
if s[start-1] == s[start+ln-1]:
f[start][start+ln] = f[start+1][start+ln-1]+2
else:
f[start][start+ln] = max(f[start+1][start+ln],f[start][start+ln-1])
return f[1][n]