516 Longest Palindromic Subsequence 最長(zhǎng)回文子序列
Description:
Given a string s, find the longest palindromic subsequence's length in s.
A subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.
Example:
Example 1:
Input: s = "bbbab"
Output: 4
Explanation: One possible longest palindromic subsequence is "bbbb".
Example 2:
Input: s = "cbbd"
Output: 2
Explanation: One possible longest palindromic subsequence is "bb".
Constraints:
1 <= s.length <= 1000
s consists only of lowercase English letters.
題目描述:
給定一個(gè)字符串 s ,找到其中最長(zhǎng)的回文子序列,并返回該序列的長(zhǎng)度蹋笼。可以假設(shè) s 的最大長(zhǎng)度為 1000 坡贺。
示例 :
示例 1:
輸入:
"bbbab"
輸出:
4
一個(gè)可能的最長(zhǎng)回文子序列為 "bbbb"惹想。
示例 2:
輸入:
"cbbd"
輸出:
2
一個(gè)可能的最長(zhǎng)回文子序列為 "bb"马昙。
提示:
1 <= s.length <= 1000
s 只包含小寫英文字母
思路:
動(dòng)態(tài)規(guī)劃
dp[i][j]表示 s[i:j + 1]中的最長(zhǎng)回文子序列
當(dāng) s[i] == s[j], dp[i][j] = dp[i + 1][j - 1] + 2
否則 dp[i][j] = max(dp[i + 1][j], dp[i][j - 1])
初始狀態(tài) dp[i][i] = 1
由于需要獲得 dp[i + 1][j - 1], 需要從后往前遍歷
時(shí)間復(fù)雜度O(n ^ 2), 空間復(fù)雜度O(n ^ 2)
代碼:
C++:
class Solution
{
public:
int longestPalindromeSubseq(string s)
{
int n = s.size();
vector<vector<int>> dp(n, vector<int>(n, 0));
for (int i = 0; i < n; i++) dp[i][i] = 1;
for (int i = n - 1; i > -1; i--) for (int j = i + 1; j < n; j++) dp[i][j] = s[i] == s[j] ? dp[i + 1][j - 1] + 2 : max(dp[i + 1][j], dp[i][j - 1]);
return dp.front().back();
}
};
Java:
class Solution {
public int longestPalindromeSubseq(String s) {
int n = s.length(), dp[][] = new int[s.length()][s.length()];
for (int i = 0; i < n; i++) dp[i][i] = 1;
for (int i = n - 1; i > -1; i--) for (int j = i + 1; j < n; j++) dp[i][j] = s.charAt(i) == s.charAt(j) ? dp[i + 1][j - 1] + 2 : Math.max(dp[i + 1][j], dp[i][j - 1]);
return dp[0][n - 1];
}
}
Python:
class Solution:
def longestPalindromeSubseq(self, s: str) -> int:
dp = [[0] * (len(s)) for _ in range(len(s))]
for i in range((n := len(s))):
dp[i][i] = 1
for i in range(n - 1, -1, -1):
for j in range(i + 1, n):
dp[i][j] = dp[i + 1][j - 1] + 2 if s[i] == s[j] else max(dp[i + 1][j], dp[i][j - 1])
return dp[0][-1]