#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;
}