Longest Palindromic Subsequence
PROBLEM :
Given a String, find the longest palindromic subsequence
Input:
The first line of input contains an integer T, denoting no of test cases. The only line of each test case consists of a string S(only lowercase)
Output:
Print the Maximum length possible for palindromic subsequence.
Constraints:
1<=T<=100
1<=|Length of String|<=1000
Examples:
Input:
2
bbabcbcab
abbaab
Output:
7
4
--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------
#include<iostream>
using namespace std;
#include<bits/stdc++.h>
int LongestPalindromicSubsequence(string ) ;
int max(int ,int ) ;
int main()
{
int t ;
cin>>t ;
while(t--){
string str ;
cin>>str ;
cout<<LongestPalindromicSubsequence(str)<<endl ;
}
return 0;
}
int LongestPalindromicSubsequence(string str){
int n=str.length() ;
int mat[n+1][n+1] ;
reverse(str.begin(),str.end());
string temp=str ;
reverse(str.begin(),str.end());
for(int i=0;i<=n;i++){
for(int j=0;j<=n;j++){
if(i==0||j==0)
mat[i][j]=0 ;
else{
if(str[i-1]==temp[j-1])
mat[i][j]=mat[i-1][j-1]+1 ;
else
mat[i][j]=max(mat[i-1][j],mat[i][j-1]) ;
}
}
}
return mat[n][n] ;
}
int max(int a,int b){
return a>b?a:b ;
}
--------------------------------------------------------------------------------
Given a String, find the longest palindromic subsequence
Input:
The first line of input contains an integer T, denoting no of test cases. The only line of each test case consists of a string S(only lowercase)
Output:
Print the Maximum length possible for palindromic subsequence.
Constraints:
1<=T<=100
1<=|Length of String|<=1000
Examples:
Input:
2
bbabcbcab
abbaab
Output:
7
4
--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------
#include<iostream>
using namespace std;
#include<bits/stdc++.h>
int LongestPalindromicSubsequence(string ) ;
int max(int ,int ) ;
int main()
{
int t ;
cin>>t ;
while(t--){
string str ;
cin>>str ;
cout<<LongestPalindromicSubsequence(str)<<endl ;
}
return 0;
}
int LongestPalindromicSubsequence(string str){
int n=str.length() ;
int mat[n+1][n+1] ;
reverse(str.begin(),str.end());
string temp=str ;
reverse(str.begin(),str.end());
for(int i=0;i<=n;i++){
for(int j=0;j<=n;j++){
if(i==0||j==0)
mat[i][j]=0 ;
else{
if(str[i-1]==temp[j-1])
mat[i][j]=mat[i-1][j-1]+1 ;
else
mat[i][j]=max(mat[i-1][j],mat[i][j-1]) ;
}
}
}
return mat[n][n] ;
}
int max(int a,int b){
return a>b?a:b ;
}
--------------------------------------------------------------------------------
Comments
Post a Comment