这是经典的dp题目,要会做!
D路通信
暴力
#include<bits/stdc++.h>
using namespace std;
string a,b;
//求公共的最长的连续的字符串
int main(){
cin >> a >> b;
int ans = 0;
for(int i = 0; i < a.size(); i++){
for(int j = 0; j < b.size(); j++){
if(a[i] == b[j]){
int res = 1;
int x = i, y = j;
while(x<a.size()&&y<b.size()&&a[++x]==b[++y]){
res++;
}
ans = max(res, ans);
}
}
}
cout << ans;
return 0;
}
dp做法
dp[i][j] = dp[i-1][j-1] + 1 if(a[i] == b[j])
= 0 else
#include<bits/stdc++.h>
using namespace std;
string a,b;
int dp[1005][1005];
//求公共的最长的连续的字符串
int main(){
cin >> a >> b;
int ans = 0;
int n = a.size(), m = b.size();
for(int i = 0; i < n; i++){
for(int j = 0; j < m; j++){
if(a[i] == b[j]){
if(i == 0 || j == 0){
dp[i][j] = 1;
}else{
dp[i][j] = dp[i-1][j-1] + 1;
}
}
else{
dp[i][j] = 0;
}
ans = max(ans, dp[i][j]);
}
}
cout << ans;
return 0;
}