Leetcode C++ 《第175场周赛-2 》5333.制造字母异位词的最小步骤数
- 题目
给你两个长度相等的字符串 s 和 t。每一个步骤中,你可以选择将 t 中的 任一字符 替换为 另一个字符。
返回使 t 成为 s 的字母异位词的最小步骤数。
字母异位词 指字母相同,但排列不同的字符串。
示例 1:
输出:s = “bab”, t = “aba”
输出:1
提示:用 ‘b’ 替换 t 中的第一个 ‘a’,t = “bba” 是 s 的一个字母异位词。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/minimum-number-of-steps-to-make-two-strings-anagram
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
- 思路
- 统计s中字符出现的次数,如果t中出现一次就抵消,最后看s中还有哪些字符没有出现够次数
- 时间复杂度o(n),n为s或t的字符长度
- 代码
class Solution {
public:
int minSteps(string s, string t) {
map<char, int> temp;
map<char, int>::iterator it;
for (int i = 0; i < s.length(); i++) {
it = temp.find(s[i]);
if (it != temp.end())
temp[s[i]]++;
else
temp.insert(make_pair(s[i], 1));
}
for (int i = 0; i < t.length(); i++) {
it = temp.find(t[i]);
if (it != temp.end()) {
if (temp[t[i]] > 0)
temp[t[i]]--;
else
temp.erase(it);
}
}
int sum = 0;
for (it=temp.begin(); it != temp.end(); it++)
sum += it->second;
return sum;
}
};