1347. Minimum Number of Steps to Make Two Strings Anagram**

1347. Minimum Number of Steps to Make Two Strings Anagram**

https://leetcode.com/problems/minimum-number-of-steps-to-make-two-strings-anagram/

题目描述

Given two equal-size strings s and t. In one step you can choose any character of t and replace it with another character.

Return the minimum number of steps to make t an anagram of s.

An Anagram of a string is a string that contains the same characters with a different (or the same) ordering.

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. 

Example 4:

Input: s = "xxyyzz", t = "xxyyzz"
Output: 0

Example 5:

Input: s = "friend", t = "family"
Output: 4

Constraints:

  • 1 <= s.length <= 50000
  • s.length == t.length
  • s and t contain lower-case English letters only.

C++ 实现 1

如果两个字符串 st, 统计它们字符的个数, 得到如下结果:

字符串 s字符串 t
a: 3a: 2
b: 4b: 5
c: 2e: 2

s 中有 3 个 a, 4 个 b 以及 2 个 c; 而 t 中含有 2 个 a, 5 个 b, 2 个 e. 那么应该如何替换呢? 首先, 由于字符串 t 中的 a 个数比 s 中的少, 所以不用替换. 由于字符串 t 中的 b 的个数比 s 中的多, 所以可以替换的次数为 5 - 4 = 1 次. 而对于字符串 t 中的字符 e 在字符串 s 中并没有, 所以替换次数为 2. 写成代码如下:

class Solution {
public:
    int minSteps(string s, string t) {
        unordered_map<char, int> A, B;
        for (int i = 0; i < s.size(); ++ i) {
            A[s[i]] ++;
            B[t[i]] ++;
        }
        int res = 0;
        // 如果字符串 s 中没有字符 p.first, 替换次数直接为 p.second
        for (auto &p : B) {
            if (!A.count(p.first)) res += p.second;
            else {
                if (p.second > A[p.first]) res += p.second - A[p.first];
            }
        }
        return res;
    }
};

观察到:

if (!A.count(p.first)) res += p.second;

// 等效如下代码, 若 A 中不存在 p.first, A[p.first] 默认为 0
res += p.second - A[p.first];

进一步简化本题的解法为:

class Solution {
public:
    int minSteps(string s, string t) {
        unordered_map<char, int> A, B;
        for (int i = 0; i < s.size(); ++ i) {
            A[s[i]] ++;
            B[t[i]] ++;
        }
        int res = 0;
        for (auto &p : B)
            res += std::max(0, p.second - A[p.first]);
        return res;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值