题目
给你两个字符串 a 和 b ,二者均由小写字母组成。一步操作中,你可以将 a 或 b 中的 任一字符 改变为 任一小写字母 。
操作的最终目标是满足下列三个条件 之一 :
a 中的 每个字母 在字母表中 严格小于 b 中的 每个字母 。
b 中的 每个字母 在字母表中 严格小于 a 中的 每个字母 。
a 和 b 都 由 同一个 字母组成。
返回达成目标所需的 最少 操作数。
这个题是力扣周赛上的一个题 刚看到的时候 没有思路 然后看题解的思路
用哈希表模拟实现
首先使用哈希表统计两个字符串的所有的字符个数
然后根据题意开始模拟
(1)a 中的 每个字母 在字母表中 严格小于 b 中的 每个字母 。
我们遍历26个字母 然后比较该字母和a和b中的先后的关系
做出统计 如果a中该字母的字母序大于目前循环的字母的字母序 我们就加上 b中相反
(2)b 中的 每个字母 在字母表中 严格小于 a 中的 每个字母 。
我们遍历26个字母 然后比较该字母和a和b中的先后的关系
做出统计 如果a中该字母的字母序小于等于目前循环的字母的字母序 我们就加上 b中相反
(3)a 和 b 都 由 同一个 字母组成。
这个比较简单 如果不同于循环的字符 我们就加上
int minCharacters(string a, string b) {
map<char, int> hash1;
map<char, int> hash2;
for (auto s : a) {
hash1[s]++;
}
for (auto s : b) {
hash2[s]++;
}
//统计完毕
//前边严格小于后边
int count1 = a.size()+b.size();
for (int i = 0; i < 26; i++) {
int ct = 0;//临时
char temp = 'a' + i;
for (auto it : hash1) {
if (it.first > temp && temp!='z') {
ct += it.second;
}
if (temp == 'z' && it.first == 'z') {
ct += it.second;
}
}
//cout<<ct<<" ";
for (auto it : hash2) {
if (it.first <= temp) {
ct += it.second;
}
}
//cout<<ct<<" "<<endl;
count1 = min(count1, ct);
}
// 前边严格大于后边
int count2 = a.size() + b.size();
for (int i = 0; i < 26; i++) {
int ct = 0;//临时
char temp = 'a' + i;
for (auto it : hash1) {
if (it.first <= temp) {
ct += it.second;
}
}
for (auto it : hash2) {
if (it.first > temp && temp!='z') {
ct += it.second;
}
if (temp == 'z' && it.first == 'z') {
ct += it.second;
}
}
count2 = min(count2, ct);
}
cout<<count1<<" "<<count2;
int ans = min(count1, count2);
//两个都是由同一个字母构成
int count3 = a.size() + b.size();
for (int i = 0; i < 26; i++) {
char temp = 'a' + i;
int ct = 0;
for (auto it : hash1) {
if (it.first != temp) {
ct += it.second;
}
}
for (auto it : hash2) {
if (it.first != temp) {
ct += it.second;
}
}
count3 = min(count3, ct);
}
return min(ans, count3);
}
希望我上边所写对大家有帮助
版权声明:本文为weixin_44302602原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。