使用dp[i][j]表示 以str1[i]和str2[j]结尾的最长公共子串的长度,因为要求子串连续,所以对于str1[i]与str2[j]来讲,它们要么与之前的公共子串构成新的公共子串;要么就是不构成公共子串。
状态转移方程
1 str1[i] == str2[j] && (0 == i || 0 == j)
dp[i][j] = dp[i-1][j-1] + 1 str1[i] == str2[j] && (i > 0 && j > 0)
0 str1[i] != str2[j]
#include <iostream>
#include <string.h>
using namespace std;
#define MAX 100
int dp[MAX][MAX] = { 0 };
void lcsubstr(char *str1, int m, char *str2, int n)
{
int maxlen = 0;
int maxindex = 0;
for (int i = 0; i < m; ++i)
for (int j = 0; j < n; ++j)
if (str1[i] == str2[j])
{
if (0 == i || 0 == j)
dp[i][j] = 1;
else
dp[i][j] = dp[i-1][j-1]+1;
if (dp[i][j] > maxlen)
{
maxlen = dp[i][j];
maxindex = i + 1 - maxlen;
}
}
cout << "maxlen = " << maxlen << " ,maxindex = " << maxindex << endl;
for (int t = 0; t < maxlen; ++t)
cout << str1[t+maxindex];
cout << endl;
}
int main()
{
char str1[] = "21232523311324";
char str2[] = "312123223445";
int m = strlen(str1);
int n = strlen(str2);
lcsubstr(str1, m, str2, n);
return 0;
}
output:
maxlen = 5 ,maxindex = 0
21232