最长公共字串。
题目:如果字符串一的所有字符按其在字符串中的顺序出现在另外一个字符串二中,
则字符串一称之为字符串二的子串。
注意,并不要求子串(字符串一)的字符必须连续出现在字符串二中。
请编写一个函数,输入两个字符串,求它们的最长公共子串,并打印出最长公共子串。
程序运行结果:
题目:如果字符串一的所有字符按其在字符串中的顺序出现在另外一个字符串二中,
则字符串一称之为字符串二的子串。
注意,并不要求子串(字符串一)的字符必须连续出现在字符串二中。
请编写一个函数,输入两个字符串,求它们的最长公共子串,并打印出最长公共子串。
例如:输入两个字符串BDCABA 和ABCBDAB,字符串BCBA 和BDAB 都是是它们的最长公共子串,则输出它们的长度4,并打印任意一个子串。
可以使用递归或者动态规划求解,递归会重复求解重叠子问题,大量的重复操作导致算法效率很低,对于长度分别为m,n的字符串,二叉递归树的高度为m+n,因此采用递归方法的复杂度达到O(2^(m+n))。
动态规划方法采用二维数组来记录前一步的计算结果,避免了重复计算,通过两个for循环就可以解决问题,算法复杂度O(mn)。
最后通过回溯操作获取具体的子串。
具体的算法原理网上有很多经典讲解,这里不再赘述。
C++实现代码:
#include "stdafx.h"
#include <iostream>
/*动态规划解决最长公共子序列的问题*/
namespace LongestCommonSubSequence
{
int LCS_Recursive(const char* s1, const char* s2, int index1, int index2) //采用递归方法
{
if (s1[index1] == '\0' || s2[index2] == '\0')
return 0;
if (s1[index1] == s2[index2])
return 1 + LCS_Recursive(s1, s2, index1 + 1, index2 + 1);
else
{
int len1 = LCS_Recursive(s1, s2, index1 + 1, index2);
int len2 = LCS_Recursive(s1, s2, index1, index2+1);
return len1 > len2 ? len1 : len2;
}
}
//采用动态规划的方法
enum direction { LEFT, UP, LEFTUP };
void printLCS(const char* s1,direction** DPDir, int i, int j)
{
if (i == 0 || j == 0) return;
if (DPDir[i][j] == LEFTUP)
{
printLCS(s1,DPDir, i - 1, j - 1);
cout << s1[i - 1] << "坐标:" << i - 1 << ' ' << j - 1 << endl;
}
else if (DPDir[i][j] == UP)
printLCS(s1, DPDir, i-1, j);
else
printLCS(s1, DPDir, i, j-1);
}
int LCS_DP(const char* s1, const const char* s2)
{
int len1 = strlen(s1);
int len2 = strlen(s2);
int **DP = (int**)malloc((len1+1)*sizeof(int*));
for (int i = 0; i <= len1; i++)
DP[i] = (int*)malloc((len2+1)*sizeof(int));
//memset(DP, 0, sizeof(DP)); 内存错误,DP不是数组名,这里相当于把指向第一行的指针修改了
for (int i = 0; i <= len1; i++)
DP[i][0] = 0;
for (int j = 0; j < len2; j++)
DP[0][j] = 0;
DP[0][0] = 1;
direction** DPDir = (direction**)malloc((len1 + 1)*sizeof(direction*));
for (int i = 0; i <=len1; i++)
DPDir[i] = (direction*)malloc((len2+1)*sizeof(direction));
int temp[8][7];
for (int i = 1; i <= len1;i++)
for (int j = 1; j <= len2; j++)
{
if (s1[i - 1] == s2[j - 1])
{
DP[i][j] = DP[i - 1][j - 1] + 1;
temp[i][j]=DPDir[i][j] = LEFTUP;
}
else if (DP[i - 1][j] >=DP[i][j - 1])
{
DP[i][j] = DP[i - 1][j];
temp[i][j] = DPDir[i][j] = UP;
}
else
{
DP[i][j] = DP[i][j - 1];
temp[i][j] = DPDir[i][j] = LEFT;
}
}
printLCS(s1, DPDir, len1, len2);
return DP[len1][len2];
}
void test()
{
const int MAX = 100;
char* s1 = "ABCBDAB";
char* s2 = "BDCABA";
char record[MAX];
int length = LCS_Recursive(s1, s2, 0, 0);
cout << length << endl;
length=LCS_DP(s1, s2);
cout << length << endl;
}
}
int _tmain(int argc, _TCHAR* argv[])
{
LongestCommonSubSequence::test();
return 0;
}
程序运行结果: