在C ++中制作两个不带字符删除的两个字符串字谜所需的最少操作数
假设我们有两个长度相等的字符串,我们必须找到使两个字符串相符的最小数目的更改,而不删除任何字符。字谜是两个具有相同字符集的字符串。假设两个字符串为“HELLO”和“WORLD”,此处需要更改的数目为3,因为在这种情况下,三个字符不同。
这个想法很简单,我们必须找到第一个字符串中每个字符的频率,然后遍历第二个字符串,如果第二个字符串中的字符存在,则在频率数组中,然后降低频率值。如果频率值小于0,则将最终计数增加1。
示例
#include <iostream>
using namespace std;
int countAlteration(string str1, string str2) {
int count = 0;
int frequency[26];
for (int i = 0; i < 26; i++){
frequency[i] = 0;
}
for (int i = 0; i < str1.length(); i++)
frequency[str1[i] - 'A']++;
for (int i = 0; i < str2.length(); i++){
frequency[str2[i] - 'A']--;
if (frequency[str2[i] - 'A'] < 0)
count++;
}
return count;
}
int main() {
string s1 = "HELLO", s2 = "WORLD";
cout << "Number of required alteration: " << countAlteration(s1, s2);
}输出结果
Number of required alteration: 3
热门推荐
10 圣诞祝福语简短小学
11 祖国七十华诞简短祝福语
12 老师送的祝福语简短
13 生日祝福语大全女生简短
14 祝女性生日祝福语简短
15 牛年女神节祝福语简短
16 情人表白祝福语简短大气
17 老公开业祝福语简短
18 官宣新年祝福语简短