[Geeks for Geeks] Longest Palindromic Subsequence

Longest Palindromic Subsequence

Given a String, find the longest palindromic subsequence.

  • Time : O(n^2)
  • Space : O(n^2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution{
int dp[505][505];
int helper(string& S, int l, int r) {
if(l > r) return 0;
if(l == r) return 1;
if(dp[l][r] != -1) return dp[l][r];
int& res = dp[l][r] = max(helper(S, l + 1, r), helper(S, l, r - 1));
if(S[l] == S[r])
res = max(res, 2 + helper(S, l + 1, r - 1));
return res;
}
public:
int longestPalinSubseq(string A) {
memset(dp, -1, sizeof dp);
return helper(A, 0, A.length() - 1);
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/26/PS/GeeksforGeeks/longest-palindromic-subsequence/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.