原题链接:字符串的修改
解体思路:
贪心
对字符串 A 的增删改都会导致操作次数 + 1,所以只需找出字符串 B 中能够对应到字符串 A 中的字符数目(即不需改动的字符),用 A.Length() - count 即可求得。
注意事项:
注意到有可能字符串 B 的第一个字符对应到字符串 A 偏后的字符,所以需要循环 B.Length() 次,忽略掉字符串 B 中的各个字符,依次求解,取最小值。
参考代码:
#include<iostream>
#include<string>
#include<cstring>
using namespace std;
const int maxn = 200 + 5;
int main(){
string a, b;
cin >> a >> b;
int ans = maxn;
for(int i = 0; i < b.length(); i ++){
int count = 0;
int posa, posb, pos = 0;
for(posb = i; posb < b.length(); posb ++){
for(posa = pos; posa < a.length(); posa ++){
if(a[posa] == b[posb]){
pos = posa + 1;
count ++;
}
}
}
ans = ans > (a.length() - count) ? (a.length() - count):ans;
}
cout << ans << endl;
return 0;
}0.0分
14 人评分
C语言网提供由在职研发工程师或ACM蓝桥杯竞赛优秀选手录制的视频教程,并配有习题和答疑,点击了解:
一点编程也不会写的:零基础C语言学练课程
解决困扰你多年的C语言疑难杂症特性的C语言进阶课程
从零到写出一个爬虫的Python编程课程
只会语法写不出代码?手把手带你写100个编程真题的编程百练课程
信息学奥赛或C++选手的 必学C++课程
蓝桥杯ACM、信息学奥赛的必学课程:算法竞赛课入门课程
手把手讲解近五年真题的蓝桥杯辅导课程
@54dsnxm #include <bits/stdc++.h> using namespace std; int main(){ string str1,str2; cin>>str1>>str2; int len1=str1.size(),len2=str2.size(); vector<vector<int> > dp(len1+1,vector<int>(len2+1,0)); for(int i=0;i<=len1;i++)dp[i][0]=i; for(int i=0;i<=len2;i++)dp[0][i]=i; for (int i=1;i<=len1;i++) { for (int j=1;j<=len2;j++) { dp[i][j]=min(min(dp[i][j-1]+1, dp[i-1][j]+1),dp[i-1][j-1]+(str1[i-1]==str2[j-1]?0:1)); } } cout<<dp[len1][len2]<<endl; return 0; }