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.
class Solution { public int minSteps(String s, String t) { int le = s.length(); Map<Character, Integer> map1 = new HashMap(); Map<Character, Integer> map2 = new HashMap(); int cont = 0; for(int i = 0; i < le; i++){ map1.put(s.charAt(i), map1.getOrDefault(s.charAt(i), 0) + 1); map2.put(t.charAt(i), map2.getOrDefault(t.charAt(i), 0) + 1); } for(Character c: map2.keySet()){ if(map1.containsKey(c)) cont += Math.min(map1.get(c), map2.get(c)); } return le - cont; } }
用两个hashmap存放character的出现次数,返回总长度 - 重合部分
class Solution { public int minSteps(String s, String t) { int n = s.length(), ans = 0; int[] arr = new int[26]; for(int i = 0; i < n; i++) { arr[s.charAt(i) - 'a']++; arr[t.charAt(i) - 'a']--; } for(int i = 0; i < 26; i++) if(arr[i] > 0) ans += arr[i]; return ans; } }
但这种比较字符类型的题目用一个长26的array更好处理