在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 送给学长毕业祝福语简短