题型1:求两个字符串的最大子串的长度
题解思路
采用最短编辑距离的方式
举例
#include <algorithm>
#include<iostream>
#include<vector>
using namespace std;
int main(){
string str1, str2;
while(cin >> str1 >> str2){
int len1 = str1.size();
int len2 = str2.size();
int max = 0;
vector<vector<int>> dp(len1 + 1, vector<int>(len2 + 1, 0));
for(int i = 1; i <= len1; ++i){
for(int j = 1; j <= len2; ++j){
if(str1[i-1] == str2[j-1]){
dp[i][j] = dp[i-1][j-1] + 1;
max = std::max(max, dp[i][j]);
}
}
}
cout << max << endl;
}
return 0;
}
题型2:求两个字符串的最大子串
题解思路
暴力循环
举例
#include<iostream>
#include<string>
#include<map>
using namespace std;
int main()
{
string s1, s2;
getline(cin, s1);
getline(cin, s2);
map<int, string> m;
for (int j = 0; j < s1.size(); ++j) {
for (int i = s1.size(); i > 0; --i) {
string temp = s1.substr(j, i);
if (s2.find(temp) != s2.npos) {
m.insert(make_pair((int)temp.size(), temp));
}
}
}
cout << m.rbegin()->second << endl;
return 0;
}