Wednesday, 26 October 2016

LONGEST PALINDROMIC SUBSEQUENCE

Hello Guys! Well! Do you know that I am on a quest of solving Dynamic Problems? And yes they have freaked me out. But nevertheless I am thoroughly enjoying the beauty of Dynamic Programming. So, I present to you yet another DP,  LONGEST PALINDROMIC SUBSEQUENCE

Problem Statement: Given a sequence, find the length of the longest palindromic sub sequence in it. For example, if the given sequence is “BBABCBCAB”, then the output should be 7 as “BABCBAB” is the longest palindromic sub sequence in it. “BBBBB” and “BBCBB” are also palindromic subsequences of the given sequence, but not the longest ones.


Another very important note: I have implemented the code in C++, I have  made it a lot easier and understandable than the rest of the general solutions on the web.

#include<iostream>
using namespace std;

int main(){
    string s ("BBABCBCAB");
    size_t l = (s.size())-1;
    int T[l][l],j,k=1;
    for(auto i = 0;i<=l;++i)
        T[i][i]=1;
    while(k<=l){
        for(auto i = 0;i<=l-k;++i){
            j = i+k;
            if (s.at(i)==s.at(j))
               T[i][j]= T[i+1][j-1] + 2;
            else
               T[i][j]= max(T[i][j-1], T[i+1][j]);
        }++k;
    }return T[0][l];
}

The Code looks Sweet, Simple and Short Isn't It? I won't brag about myself I leave that on to you.

No comments:

Post a Comment