20240112-补 制作两个字符串字谜的最少步骤数

题目要求

给你两个长度相同的字符串 s 和 t。在一个步骤中,你可以选择 t 中的任意一个字符并用另一个字符替换它。

返回将 t 变为 s 的变位所需的最少步数。

字符串的 "字谜 "是指字符串中的相同字符具有不同(或相同)的排列顺序。

Example 1:

Input: s = "bab", t = "aba"
Output: 1
Explanation: Replace the first 'a' in t with b, t = "bba" which is anagram of s.

Example 2:

Input: s = "leetcode", t = "practice"
Output: 5
Explanation: Replace 'p', 'r', 'a', 'i' and 'c' from t with proper characters to make t anagram of s.

Example 3:

Input: s = "anagram", t = "mangaar"
Output: 0
Explanation: "anagram" and "mangaar" are anagrams. 

思路

看起来非常的简单,用哈希表统计每个字符出现的次数,如果字母a在单词bbb中没出现过,那么次数即为零。统计两个字符串相同字母出现次数的差值,相加除以2就是我们所需要的答案。

代码

class Solution {
public:
    int minSteps(string s, string t) {
        int ans = 0;
        unordered_map<char, int> map1, map2;
        for (int i = 0; i < s.size(); ++i) {
            map1[s[i]]++;
            map2[t[i]]++;
        }
        for (auto p : map1) {
            ans += abs(p.second - map2[p.first]);
        }
        for (auto p : map2) {
            if (map1.find(p.first) == map1.end()) {
                ans += p.second;
            }
        }
        return int(ans/2);
    }
};

时空复杂度

  • 8
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值