๐ 516. ๆ้ฟๅๆๅญๅบๅ
2022ๅนด6ๆ9ๆฅๅฐไบ 1 ๅ้
๐ 516. ๆ้ฟๅๆๅญๅบๅ
้พๅบฆ: ๐
้ฎ้ขๆ่ฟฐ
่งฃๆณ
class Solution {
public int longestPalindromeSubseq(String s) {
// ๆ่ทฏ๏ผ
// dp[i][j] = dp[i + 1][j - 1] + 2
// dp[i][j] = max(dp[i + 1][j], dp[i][j - 1], dp[i + 1][j - 1])
int len = s.length();
int[][] dp = new int[len][len];
// ๅๅงๅ
// dp
for(int i = len - 1; i >= 0; i --) {
for(int j = i; j < len; j ++) {
if(i == j) {
dp[i][j] = 1;
} else if(i == j - 1) {
if(s.charAt(i) == s.charAt(j)) {
dp[i][j] = 2;
} else {
dp[i][j] = 1;
}
} else {
if(s.charAt(i) == s.charAt(j)) {
dp[i][j] = dp[i + 1][j - 1] + 2;
} else {
dp[i][j] = Math.max(dp[i + 1][j], Math.max(dp[i][j - 1], dp[i + 1][j - 1]));
}
}
}
}
return dp[0][len - 1];
}
}