您的位置:首页 > 其它

最长公共子序列LCS

2011-11-24 12:24 411 查看
//LCS算法,最长公共子序列 来自《算法导论》

#include<iostream>
#include<cstdlib>
#include<cmath>
#define N 105
char s[N+1][N+1];
using namespace std;
int LCS( const char*s1,const char*s2){
int m = strlen(s1);
int n = strlen(s2);
int i,j;
s[0][0]=0;
for( i = 0;i <= m;i++){
s[i][0]=0;
}
for( j = 0;j <= n;j++){
s[0][j]=0;
}
for( i = 1;i <= m;i++){
for( j = 1;j <= n;j++){
if(s1[i]==s2[j]){
s[i][j]=s[i-1][j-1]+1;
}
else if(s[i-1][j]>s[i][j-1]){
s[i][j]=s[i-1][j];
}
else {
s[i][j]=s[i][j-1];
}

}
}
return s[m]
;
}

int main(){
char s1
,s2
;
while( cin >> s1 >> s2){
cout << LCS(s1,s2) << endl;
}
system("pause");
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: