【LeetCode】满足三个条件之一需改变的最少字符数

题目

给你两个字符串 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);
    }

希望我上边所写对大家有帮助

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值