使用C ++将一个字符串转换为另一个字符串的最小删除和插入次数。
描述
给定两个分别为m和n的字符串str1和str2。任务是从str1中/在str1中删除并插入最少数量的字符,以便将其转换为str2。
Str1 = “nhooo” Str2 = “tutorials” To transform str1 to str2 we have to delete five characters i.e. “point” from str1.
算法
1. Find longest common subsequence of str1 and str2. Let’s call it as “lcsSize” 2. Number of characters to be deleted = (length of str1 - lcsSize) 3. Number of characters to be inserted = (length of str2 - lcsSize)
示例
#include <iostream>
#include <algorithm>
using namespace std;
int lcs(string s1, string s2, int m, int n){
if (m == 0 || n == 0) {
return 0;
}
if (s1[m - 1] == s2[n - 1]) {
return 1 + lcs(s1, s2, m - 1, n - 1);
} else {
return max(lcs(s1, s2, m, n - 1), lcs(s1, s2, m - 1, n));
}
}
void minDeletionAndInsertion(string s1, string s2){
int m = s1.size();
int n = s2.size();
int lcsSize = lcs(s1, s2, m, n);
cout << "Min deletion = " << (m - lcsSize) << endl;
cout << "Min insertion = " << (n - lcsSize) << endl;
}
int main(){
minDeletionAndInsertion("nhooo", "tutorials");
return 0;
}输出结果
当您编译并执行上述程序时。它生成以下输出-
Min deletion = 5 Min insertion = 0
热门推荐
6 保研的祝福语简短
10 年轻20岁祝福语简短
11 朋友结婚祝福语信息简短
12 女孩婚礼贺卡祝福语简短
13 30段点歌简短祝福语
14 虎年春节祝福语图文简短
15 写给后妈祝福语大全简短
16 简短回复生日祝福语
17 校长送毕业祝福语简短
18 毕业立体贺卡祝福语简短