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;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章