//autor:baker
//time:25/5/06
//email:[email protected]
/* 求兩個字符串的最長公共子序列。
X的一個子序列是相應於X下標序列{1, 2, …, m}的一個子序列,求解兩個序列的所有子序列中長度最大的,例如輸入:pear, peach輸出:pea。
分析:
次題可用動態規劃算法解決。
首先定義一個二維數組:A【】【】;
A[i][j] |
M |
G |
D |
D |
G |
0 |
1 |
0 |
0 |
g |
0 |
1 |
0 |
0 |
d |
0 |
0 |
2 |
1 |
d |
0 |
0 |
0 |
3 |
如上,A[I][J]表示在此字符以前互相匹配的字符數目,當MAX=MAX(MAX,A[I][J])爲最大時,即求得最大匹配子串。
當STR1[I]=STR2[J]時,A[I][J]=A[I-1][J-1]+1,即左上方最大匹配字符數目加一。
當MAX爲最大時,記錄下當前掃描STR1的位置爲TAG
(2)源代碼如下:
*/
#include"iostream"
#include"conio.h"
#include"string"
using namespace std;
void maxstring(string str1,string str2)
{
int max=0,tag,i,j;
int length1=str1.size();
int length2=str2.size();
int a[length1+1][length2+1];
for(i=0;i<=length1;i++)
for(j=0;j<=length2;j++)
a[i][j]=0;
for(i=1;i<=length1;i++)
for(j=1;j<=length2;j++)
if(str1[i]==str2[j])
{
a[i][j]=a[i-1][j-1]+1;
if(max<a[i][j])
{
max=a[i][j];
tag=i;
}
}
if(max==0){cout<<"no found same string!";return ;}
cout<<"output the max same string:";
for(i=tag-max;i<=tag;i++)
cout<<str1[i];
cout<<endl<<"the length is:"<<max<<endl;
}
int main()
{
string str1,str2;
cout<<"enter the two strings!"<<endl;
cout<<"string 1:";
cin>>str1;
cout<<"string 2:";
cin>>str2;
maxstring(str1,str2);
getch();
return 0;
}
/*(4)程序截圖:
*/