原题链接在这里:https://leetcode.com/problems/minimum-number-of-steps-to-make-two-strings-anagram-ii/
题目:
You are given two strings s
and t
. In one step, you can append any character to either s
or t
.
Return the minimum number of steps to make s
and t
anagrams of each other.
An anagram of a string is a string that contains the same characters with a different (or the same) ordering.
Example 1:
Input: s = "leetcode", t = "coats" Output: 7 Explanation: - In 2 steps, we can append the letters in "as" onto s = "leetcode", forming s = "leetcodeas". - In 5 steps, we can append the letters in "leede" onto t = "coats", forming t = "coatsleede". "leetcodeas" and "coatsleede" are now anagrams of each other. We used a total of 2 + 5 = 7 steps. It can be shown that there is no way to make them anagrams of each other with less than 7 steps.
Example 2:
Input: s = "night", t = "thing" Output: 0 Explanation: The given strings are already anagrams of each other. Thus, we do not need any further steps.
Constraints:
1 <= s.length, t.length <= 2 * 105
s
andt
consist of lowercase English letters.
题解:
Map the count for char in s and t.
Accumlate the difference to res.
Time Complexity: O(n). n = s.length().
Space: O(1).
AC Java:
1 class Solution { 2 public int minSteps(String s, String t) { 3 int [] map = new int[26]; 4 for(int i = 0; i < s.length(); i++){ 5 map[s.charAt(i) - 'a']++; 6 } 7 8 for(int i = 0; i < t.length(); i++){ 9 map[t.charAt(i) - 'a']--; 10 } 11 12 int res = 0; 13 for(int num : map){ 14 res += Math.abs(num); 15 } 16 17 return res; 18 } 19 }
类似Minimum Number of Steps to Make Two Strings Anagram.
标签:anagrams,int,res,Make,Number,other,steps,each,Strings From: https://www.cnblogs.com/Dylan-Java-NYC/p/16632937.html