You are given two strings of the same length 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.
Constraints:
1 <= s.length <= 5 * 104
s.length == t.length
s
andt
consist of lowercase English letters only.
思路:为什么只用加正数,就是因为正负数是抵消的;因为长度相等,一个出现在a是+1, 一个出现在b, -1;
It seems like you missed the main constraint in the question that says s and t are of the same length.
So arr[i] positive means t is deficient of those characters and they need to be added to make it same
arr[i] is negative means t is in surplus of those characters and they need to be replaced. a
you could have done if(arr[i] < 0 ) ans+=arr[i] and then returned -1*ans as well and it would have resulted in same ans
consider an example abcde and aaabd
so your array will look like [-2,0,1,0,1]
so you can see that sum of negative and postive is always the same
class Solution {
public int minSteps(String s, String t) {
HashMap<Character, Integer> hashmap = new HashMap<>();
for(int i = 0; i < s.length(); i++) {
char sc = s.charAt(i);
char tc = t.charAt(i);
hashmap.put(sc, hashmap.getOrDefault(sc, 0) + 1);
hashmap.put(tc, hashmap.getOrDefault(tc, 0) - 1);
}
int cost = 0;
for(Character key: hashmap.keySet()) {
if(hashmap.get(key) > 0) {
cost += hashmap.get(key);
}
}
return cost;
}
}