Minimum Number of Steps to Make Two Strings Anagram

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 and t 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;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值