題目描述:
給你兩個長度相等的字符串 s 和 t。每一個步驟中,你可以選擇將 t 中的 任一字符 替換爲 另一個字符。
返回使 t 成爲 s 的字母異位詞的最小步驟數。
字母異位詞 指字母相同,但排列不同的字符串。
示例 1:
輸出:s = “bab”, t = “aba”
輸出:1
提示:用 ‘b’ 替換 t 中的第一個 ‘a’,t = “bba” 是 s 的一個字母異位詞。
示例 2:
輸出:s = “leetcode”, t = “practice”
輸出:5
提示:用合適的字符替換 t 中的 ‘p’, ‘r’, ‘a’, ‘i’ 和 ‘c’,使 t 變成 s 的字母異位詞。
示例 3:
輸出:s = “anagram”, t = “mangaar”
輸出:0
提示:“anagram” 和 “mangaar” 本身就是一組字母異位詞。
示例 4:
輸出:s = “xxyyzz”, t = “xxyyzz”
輸出:0
示例 5:
輸出:s = “friend”, t = “family”
輸出:4
提示:
1 <= s.length <= 50000
s.length == t.length
s 和 t 只包含小寫英文字母
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/minimum-number-of-steps-to-make-two-strings-anagram
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。
使用map存儲兩個字符串出現的字符次數
class Solution {
public int minSteps(String s, String t) {
int result = 0;
Map<Character,Integer> map = new HashMap<>();
Map<Character,Integer> mapt = new HashMap<>();
for (int i = 0; i < s.length(); i++) {
map.put(s.charAt(i),map.getOrDefault(s.charAt(i),0) + 1);
mapt.put(t.charAt(i),mapt.getOrDefault(t.charAt(i),0) + 1);
}
for (Map.Entry<Character,Integer> characterIntegerEntry : map.entrySet()) {
char key = characterIntegerEntry.getKey();
int num1 = characterIntegerEntry.getValue();
int num2 = mapt.getOrDefault(key,0);
if(num1 > num2){
result += num1 - num2;
}
}
return result;
}
}