Skip to content

Instantly share code, notes, and snippets.

@theSundayProgrammer
Last active March 23, 2020 06:22
Show Gist options
  • Save theSundayProgrammer/de4d22ca4f0d8e1192c08fd3918b536f to your computer and use it in GitHub Desktop.
Save theSundayProgrammer/de4d22ca4f0d8e1192c08fd3918b536f to your computer and use it in GitHub Desktop.
Problem 15.5 from Cormen's book: longest palindromic sequence
/**
For example if the input is "charachter" the output shout be "carac"
*/
#include <iostream>
#include <string>
class CostArray{
int *cost;
int width;
public:
CostArray(int m, int n):width(n){
cost = new int[m*n] ;
}
int get(int i, int j) const{
if (i<0 || j<0) return 0;
else return cost[i*width+j];
}
void set(int i, int j, int val){
cost[i*width+j] = val;
}
};
using std::string;
CostArray ComputeArray(string const& X, string const& Y){
CostArray cost(X.length(),Y.length());
for(int i=0; i<X.length(); ++i)
for(int j=0; j<Y.length(); ++j){
if(X[i] == Y[j]){
cost.set(i,j,cost.get(i-1,j-1)+1);
}else {
int x = cost.get(i-1,j);
int y = cost.get(i,j-1);
cost.set(i,j,std::max(x,y));
}
}
return cost;
}
void PrintSequence(CostArray const& cost, string const& X, string const& Y, int i, int j){
if(i<0 || j<0) return;
else if(X[i]==Y[j]){
PrintSequence(cost,X,Y,i-1,j-1);
std::cout << X[i];
}else if( cost.get(i-1,j)<cost.get(i,j-1)){
PrintSequence(cost, X,Y,i,j-1);
} else {
PrintSequence(cost,X,Y,i-1,j);
}
}
int test(int argc, char* argv[]){
if (argc<3){
std::cout << "requires two string arguments" << "\n";
}
string X=argv[1];
string Y=argv[2];
CostArray cost = ComputeArray(X,Y);
PrintSequence(cost,X,Y,X.length()-1,Y.length()-1);
return 0;
}
int main(int argc, char* argv[]){
if (argc<2){
std::cout << "requires one string argument" << "\n";
}
string X=argv[1];
string Y(X.rbegin(),X.rend());
std::cout << X << " " << Y << "\n";
CostArray cost = ComputeArray(X,Y);
PrintSequence(cost,X,Y,X.length()-1,Y.length()-1);
std::cout<<std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment