算法:最大公共字串求解

来源:互联网 发布:linux 编译环境 编辑:程序博客网 时间:2024/06/05 00:12

在实际生活中我们往往需要对两个字串求最大的公共字串,这时候就需要一个算法来帮助我们完成。

首先定义两个字符串x,y.

再定义两个数组b,c。其中c数组的作用在于记录最大字串长度,方便进行比较找到局部最优解,b数组的作用在于输出和记录上一个公共字串的位置。

每当x对应元素和y元素相等,b,c对应行列中就将进行相应操作,c数组将之前【i-1】【j-1】位置的值加1,代表最长公共子序列长度加1,b赋值为1。

当x与y不等时,对c【i-1】【j】和c【j-1】【i】进行比较,把较大的记录下来,代表当前最长子序列,并且在进行回溯的时候用数组b进行标记哪个为最优。

注意:

b和c数组的行为x的长度,列为y的长度。其中【0】行和【0】列位置空下,字符串x【0】位置也要空下。也可都前移。

回溯时对c数组右下角数组先进行递归,cout运用技巧。


C++代码:(VS2013)

// ConsoleApplication1.cpp : 定义控制台应用程序的入口点。
//


#include "stdafx.h"
#include "iostream"
using namespace std;
const int max_length = 50;
/*
---求出最大的公共子序列长度
m, n分别为字符串x, y的长度
二维数组(m*n)c存放当前公共子序列长度,
  b存放由哪个字符导出的序列1代表上两个字符相等
2(3)表示两个字符不相等,标记上个字符为哪个位置同列或同行
*/
void LCSLength(int m, int n, char *x, char *y, int **c, int **b)
{
//i为行,j为列
int i, j;
for (i = 1; i <= m; i++)
c[i][0] = 0;
for (i = 1; i <= m; i++)
c[0][i] = 0;
for (i = 1; i <= m; i++)
for (j = 1; j <= n; j++)
{
if (x[i] == y[j]){
c[i][j] = c[i - 1][j - 1];
b[i][j] = 1;
}
else if (c[i - 1][j] >= c[i][j - 1]){
c[i][j] = c[i - 1][j];
b[i][j] = 2;
}
else{
c[i][j] = c[i][j - 1];
b[i][j] = 3;
}
}
}


/*
---输出所有序列,回溯,当b中对应值为1,则代表两值相等,直接输出
i, j初始值为m, n
*/
void LCS(int i, int j, char *x, int **b)
{
if (i == 0 || j == 0)return;
if (b[i][j] == 1){
LCS(i - 1, j - 1, x, b);
cout << x[i];
}
else if (b[i][j] == 2)
LCS(i - 1, j, x, b);
else LCS(i, j - 1, x, b);
}
/*
--获取传入字符串的长度,并把第一位空出来
*/
int strlength(char *s)
{
char *x = new char[2];
int i = 0;
x[0] = ' ';
while (s[i] != '\0')
{
x[1] = s[i];
s[i] = x[0];
x[0] = x[1];
i++;
}
s[i] = x[0];
delete x;
return i;
}






int _tmain(int argc, _TCHAR* argv[])
{
char *x = new char[max_length+1];
cin >> x;
char *y = new char[max_length+1];
cin >> y;
int x_length = strlength(x);
int y_length = strlength(y);
int **b = new  int *[x_length+1];
int **c = new  int *[x_length+1];
for (int i = 0; i < x_length+1; i++)
{
b[i] = new int[y_length+1];
c[i] = new int[y_length+1];
}
LCSLength(x_length, y_length, x, y, c, b);
LCS(x_length, y_length, x, b);
delete x, y;
delete[] b, c;
return 0;
}


0 0
原创粉丝点击