Longest Palindromic Subsequence in C++


Suppose we have a string s, we have to find the longest palindromic subsequence's length in s. We can assume that the maximum length of s is 1000. So if the input is like “bbbab”, then output will be 4. One possible palindromic subsequence is “bbbb”.

To solve this, we will follow these steps −

  • x := s, then reverse x, n := size of s
  • if n is 0, then return 0
  • update s by adding one blank space before s, and update x by adding one blank space before x
  • ret := 0
  • make one matrix dp of size (n + 1) x (n + 1)
  • for i in range 1 to n
    • for j in range n to n
      • dp[i, j] := max of dp[i, j – 1], dp[i – 1, j]
      • if x[i] = s[j], then dp[i, j] := max of dp[i, j] and 1 + dp[i – 1, j – 1]
  • return dp[n, n]

Let us see the following implementation to get better understanding −

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   int longestPalindromeSubseq(string s) {
      string x = s;
      reverse(x.begin(), x.end());
      int n = s.size();
      if(!n) return 0;
      s = " " + s;
      x = " " + x;
      int ret = 0;
      vector < vector <int> > dp(n + 1, vector <int>(n + 1));
      for(int i = 1; i <= n; i++){
         for(int j = 1; j <= n ; j++){
            dp[i][j] = max(dp[i][j - 1], dp[i - 1][j]);
            if(x[i] == s[j]) {
               dp[i][j] = max(dp[i][j], 1 + dp[i - 1][j - 1]);
            }
         }
      }
      return dp[n][n];
   }
};
main(){
   Solution ob;
   cout << (ob.longestPalindromeSubseq("bbbab"));
}

Input

"bbbab"

Output

4

Updated on: 02-May-2020

582 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements