您的位置:首页 > 产品设计 > UI/UE

最长公子序列 Longest Common Subsequence

2013-02-26 02:08 337 查看
设 X = (x0, x1, ... , x_(n-1) ), Y = (y0, y1, ... , y_(m-1) ), 那么用动态规划的方法,可以得到如下的阶段决策方程:



代码如下:

#include<stdio.h>
#include<stdlib.h>
#include<iostream>
#include <cstring>

using namespace std;

int LCSubsequence(char* s1, char* s2){
if(!s1 || !s2) return 0;
int len1 = strlen(s1);
int len2 = strlen(s2);
int* table = new int[len1*len2];

bool flag = false;

for(int i=0; i<len2; i++){
if(*s1==*(s2+i))
flag = true;
if(flag)
table[i] = 1;
}

flag = false;
for(int i=0; i<len1; i++){
if(*(s1+i)==*s2)
flag = true;
if(flag)
table[i*len2] = 1;
}

if(len1>1 && len2>1)
for(int i=1; i<len1; i++)
for(int j=1; j<len2; j++)
( *(s1+i)==*(s2+j) )?( table[i*len2+j] = 1+ table[(i-1)*len2+j-1]): (
table[i*len2+j] = max( table[i*len2+j-1], table[(i-1)*len2+j]) );
int temp = table[len1*len2-1];

//	delete [] table;
return temp;
}

int main()
{
char* s1 = "abcdrgth";
char* s2 = "bdacrh45";
cout<<LCSubsequence(s1, s2)<<endl;
getchar();
return 0;
}
上面的LCSubsequence函数,动态申请了一个一维数组table,用table来模拟二维数组。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: