最长回文子序列
2014-03-15 14:54
393 查看
#include <iostream> #include <ctime> using namespace std; void longest_palindrome(char *s,int **p,int length) { for(int i=0;i<length-1;++i){//初始化数组相关信息 p[i][i]=1; int j=i+1; if(s[i]==s[j]){ p[i][j]=2; }else{ p[i][j]=1; } } p[length-1][length-1]=1; //for(int i=length-3;i>=0;--i){//从后往前 // for(int l=i+2;l<length;l++){ // if(s[i]==s[l]){ // p[i][l]=p[i+1][l-1]+2; // }else if(p[i+1][l]>p[i][l-1]){ // p[i][l]=p[i+1][l]; // }else{ // p[i][l]=p[i][l-1]; // } // } //} for(int l=3;l<=length;l++){//长度1和2都已记录,此处长度由3开始,从前往后 for(int i=0;i<length-l+1;i++){ int j=i+l-1; if(s[i]==s[j]){ p[i][j]=p[i+1][j-1]+2; }else if(p[i+1][j]>p[i][j-1]){ p[i][j]=p[i+1][j]; }else{ p[i][j]=p[i][j-1]; } } } } void print_longest_palindrome(int **p,char *c,int n)//打印最长回文字符串 { int length=p[0][n-1]; char *cc=new char[length+1]; cc[length]='\0'; int i=0,j=n-1;//保存位置 int low=0,high=length-1;//回文字符串中的上下下标 while (i<j){ while (p[i][j]==p[i+1][j]){ ++i; } cc[low++]=c[i]; while(p[i][j]==p[i][j-1]){ --j; } cc[high--]=c[j]; ++i; --j; } if(low==high){ cc[low]=c[i]; } for(int k=0;k<length;++k){ cout<<cc[k]; } cout<<endl; delete []cc; } int main() { srand((unsigned)time(NULL)); int n=23; n=rand()%20+20; char *s=new char ; /*s[0]='n',s[1]='m',s[2]='g',s[3]='s',s[4]='v',s[5]='g', s[6]='r',s[7]='i',s[8]='s',s[9]='m',s[10]='y',s[11]='g',s[12]='x', s[13]='p',s[14]='p',s[15]='e',s[16]='j',s[17]='x',s[18]='p',s[19]='q', s[20]='j',s[21]='a',s[22]='i';*/ for(int i=0;i<n;++i){ //if(rand()%2){ s[i]=rand()%26+'a'; cout<<s[i]; /*}else{ s[i]=rand()%26+'A'; cout<<s[i]; }*/ } cout<<endl; int **p=new int* ; for(int i=0;i<n;++i){//存储最长回问字符长度信息,并用此构建最长回文字符串 p[i]=new int ; } for(int i=0;i<n;++i){ for(int j=0;j<n;++j){ p[i][j]=0; } } longest_palindrome(s,p,n); for(int i=0;i<n;++i){ for(int j=0;j<n;++j){ cout<<p[i][j]<<" "; } cout<<endl; } cout<<endl; print_longest_palindrome(p,s, n); delete[]s; for(int i=0;i<n;++i){ delete []p[i]; } delete[]p; }
相关文章推荐
- POJ 3264 线段树 基础入门
- VS2013 中生成lib和dll库文件
- 李开复:算法的力量
- andrioid 创建等待框
- 屏蔽 TextBox自带右键菜单
- 并发导论
- Kinect for Windows SDK开发入门(一):开发环境配置
- 【Unity3D】【NGUI】2.x升级到3.x流程
- 原码,反码,补码
- PHP的类自动加载机制
- /var/lock/subsys作用
- TOJ:Prairie dogs
- SQLite学习手册 - 自增与主键
- Quotations中页面弹出的问题
- 算法易错点:二分代码/奇偶调顺序/查找第一次出现的字符
- java“抓布娃娃的夹子”(迭代器Iterator)
- 读书笔记_Effective_C++_条款三十九:明智而审慎地使用private继承
- QT 多线程程序设计
- Java 判断文件夹、文件是否存在、否则创建文件夹
- spring mvc 获取上下文路径