在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 老公平安祝福语简短