两个字符串的最长公共子串求法(C++动态规划)
Posted AdamDuncan
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了两个字符串的最长公共子串求法(C++动态规划)相关的知识,希望对你有一定的参考价值。
#include<iostream>
#include<algorithm>
#include<string>
#include<stdlib.h>
#include<cmath>
using namespace std;
int main()
{
string str1, str2;
string shortString, longString;
//cin>>str1>>str2;
str1 = "dabcf";
str2 = "aabe";
if (str1.length() > str2.length())
{
shortString = str2;
longString = str1;
}
else {
shortString = str1;
longString = str2;
}
int longlength = longString.length();
const int shortlength = shortString.length();
int **array = new int*[longlength];
for (int i = 0; i < longlength; i++)
{
array[i] = new int[shortlength];
}
int maxIndex = 0, maxNum = 0;
for (int i = 0; i < shortlength; i++)
{
if (shortString[i] != longString[0])
{
array[0][i] = 0;
cout << "array[0][" << i << "]" << array[0][i] << " ";
}
else {
maxNum = 1;
maxIndex = i;
for (; i < shortlength; i++)
{
array[0][i] = 1;
cout << "array[0][" << i << "]" << array[0][i] << " ";
}
break;
}
}
cout << endl;
for (int i = 0; i < longlength; i++)
{
if (shortString[0] != longString[i])
{
array[i][0] = 0;
cout << "array[" << i << "]" << "[0]" << array[i][0] << " ";
}
else {
/*if (i > maxNum)
{
maxNum = 1;
maxIndex = i;
}*/
for (; i < longlength; i++)
{
array[i][0] = 1;
cout << "array[" << i << "]" << "[0]" << array[i][0] << " ";
}
break;
}
}
for (int i = 1; i < longlength; i++)
{
for (int j = 1; j < shortlength; j++)
{
int maxTemp = 0;
maxTemp = max(array[i - 1][j], array[i][j - 1]);
cout<<"max(array[i - 1][j], array[i][j - 1])" <<i-1<<","<<j<<" "<<array[i -1][j]<<" "<<
i<<","<<j - 1<<array[i][j - 1]<<endl;
cout << maxTemp << endl;
if (shortString.substr(j, maxTemp + 1) == longString.substr(i, maxTemp + 1))
{
cout << shortString.substr(j , maxTemp + 1);
array[i][j] = maxTemp + 1;
if (array[i][j] > maxNum)
{
maxNum = array[i][j];
maxIndex = j;
}
}
else {
array[i][j] = maxTemp;
}
}
}
cout<<"两个字符串的公共子串是:"<<endl;
cout << shortString.substr(maxIndex, maxNum);
//system("pause");
return 0;
}
以上是关于两个字符串的最长公共子串求法(C++动态规划)的主要内容,如果未能解决你的问题,请参考以下文章