Longest Palindromic Subsequence

Longest Palindromic Subsequence

Longest Palindromic Subsequence - DP on Strings

https://www.codingninjas.com/studio/problems/longest-palindromic-subsequence_842787?utm_source=striver&utm_medium=website&utm_campaign=a_zcoursetuf

My approach:

Reverse the original string and use LCS algorithm to find length of longest common subsequence in the original string and reverse string.

Code:

string reverse(string str){
    int s = 0;
    int e = str.size()-1;

    while(s<=e){
        char temp = str[s];
        str[s] = str[e];
        str[e] = temp;
        s++;
        e--;
    }
    return str;
}

int longestPalindromeSubsequence(string s)
{
    // Write your code here.
    int n = s.size();

    vector<vector<int>> dp(n+1, vector<int>(n+1,0));

    string revStr = reverse(s);.

    for(int i=1;i<=n;i++){
        for(int j=1;j<=n;j++){
            if(s[i-1]==revStr[j-1]){
                dp[i][j] = 1+dp[i-1][j-1];
            }else{
                dp[i][j] = max(dp[i-1][j], dp[i][j-1]);
            }
        }
    }

    return dp[n][n];
}