题意:
给定两个字符串,求他们之间的最长的相同字符串的长度。
公共子串和公共子序列是不一样的,公共子串要求连续,而公共子序列不要求连续。
示例:
输入:“helloworld”,“loop”
输出:2
解释:最长公共子串是lo
解析:
如图所示,假设结果对应一个数组dp[m][n],这个表格表示的就是A[i]和B[j]对应的字符是否相等。如果A[i] == B[j]那么dp[i][j] = dp[i-1][j-1]+1,否则为0.
dp[i][j]表示只考虑字符串A的前i个字符和字符串B的前j个字符的最大公共子串。
ps:在程序实现的时候注意细节,数组的下标及越界问题。
该理解相当于,以A[i]和B[j]结尾的公共子串的长度。
Solution:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
string str1;
string str2;
cin >> str1 >> str2;
int n1 = str1.size();
int n2 = str2.size();
vector<vector<int>> dp(n1+1,vector<int> (n2+1));//特别注意
int res = 0;
for (int i = 0; i < n1; ++i)
{
for (int j = 0; j < n2; ++j)
{
if (str1[i] == str2[j]) dp[i+1][j+1] = dp[i][j] + 1;
else
dp[i+1][j+1] = 0;
res = max(res, dp[i+1][j+1]);
}
}
cout << res << endl;
return 0;
}