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
andt
contain lower-case English letters only.
C++ 实现 1
如果两个字符串 s
和 t
, 统计它们字符的个数, 得到如下结果:
字符串 s | 字符串 t |
---|---|
a: 3 | a: 2 |
b: 4 | b: 5 |
c: 2 | e: 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;
}
};