54 Minimum Number of Steps to Make Two Strings Anagram

题目

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 and t contain lower-case English letters only.

分析

题意:t和s具有相同的字母(不考虑顺序),t就是s的Anagram。
给出t需要变几个字母才能成为s的Anagram。

算法:
一共就26个字母,只需要构造一个26位的数组,数组的下标0~25分别表示a~z,然后遍历s,让数组对应下标位置++。
接着遍历t让数组对应所在位有值的部分–。
最后对数组元素求和即可。

解答

class Solution {
    public int minSteps(String s, String t) {
        int[] flags = new int[26];
        for(char c:s.toCharArray()){
            flags[c-'a']++;
        }
        for(char c:t.toCharArray()){
            if(flags[c-'a']>0){
                flags[c-'a']--;
            }
        }
        int sum=0;
        for(int i=0;i<26;++i){
            sum+=flags[i];
        }
        return sum;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值