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

更新于:2019年10月21日

411 次浏览

开启你的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.