516. Longest Palindromic Subsequence
Problem statement:
Given a string s, find the longest palindromic subsequence's length in s. You may assume that the maximum length of s is 1000.
Example 1:
Input:
"bbbab"
Output:
4
One possible longest palindromic subsequence is "bbbb".
Example 2:
Input:
"cbbd"
Output:
2
One possible longest palindromic subsequence is "bb".
Solution:
This is a dynamic programming problem. The key point also is to find the dynamic formula. Although there is only one string, but we need a two dimension array. The value in diagonal is 1 and we only need right up part above diagonal.
dp[i][j] means the max subsequence from position i to j. The formula is:
dp[i][j] = dp[i + 1][j - 1] if s[i] == s[j]
= max(dp[i + 1][j], dp[i][j + 1]) if s[i] != s[j]
Since there is i + 1 and j - 1 is essential for current dp[i][j], we should do DP from bottom to up, left to right.
The time complexity is O(n*n), n is the size of string.
class Solution { public: int longestPalindromeSubseq(string s) { int size = s.size(); vector<vector<int>> dp(size, vector<int>(size, 0)); for(int i = 0; i < size; i++){ dp[i][i] = 1; } for(int i = size - 2; i >= 0; i--){ for(int j = i + 1; j < size; j++){ if(s[i] == s[j]){ dp[i][j] = dp[i + 1][j - 1] + 2; } else { dp[i][j] = max(dp[i + 1][j], dp[i][j - 1]); } } } return dp[0][size - 1]; } };
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步