思路
状态转移方程:
f[i][j] = 1 + f[i - 1][j - 1]
代码
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str1, str2;
while(cin >> str1 >> str2)
{
int row = str1.size();
int cloumn = str2.size();
if (row == 0 || cloumn == 0)
{
cout << endl;
continue;
}
int** record = new int*[row];
for (int i = 0; i < row; ++i)
{
record[i] = new int[cloumn];
record[i][0] = str1[i] == str2[0] ? 1 : 0;
}
for (int i = 0; i < cloumn; ++i)
{
record[0][i] = str2[i] == str1[0] ? 1 : 0;
}
int max = 0;
int maxEnd = 0;
int type = row > cloumn? 0 : 1; // 0 -> 2 1 -> 1
for (int i = 1; i < row; ++i)
{
for (int j = 1; j < cloumn; ++j)
{
if (str1[i] == str2[j])
{
record[i][j] = 1 + record[i-1][j-1];
if (max < record[i][j])
{
max = record[i][j];
maxEnd = type ? i : j;
}
else if (max == record[i][j])
{
int end = type ? i : j;
maxEnd = end < maxEnd ? end : maxEnd;
}
}
else
{
record[i][j] = 0;
}
}
}
if (type)
{
cout << str1.substr(maxEnd - max + 1, max) << endl;
}
else
{
cout << str2.substr(maxEnd - max + 1, max) << endl;
}
}
}