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.
Solution: Hashtable
Record the frequency difference of each letter.
Ans = sum(diff)
Time complexity: O(m + n)
Space complexity: O(26)
C++
1 2 3 4 5 6 7 8 9 10 11 12 13 |
// Author: Huahua class Solution { public: int minSteps(string s, string t) { vector<int> diff(26); for (char c : s) ++diff[c - 'a']; for (char c : t) --diff[c - 'a']; int ans = 0; for (int d : diff) ans += abs(d); return ans; } }; |
请尊重作者的劳动成果,转载请注明出处!花花保留对文章/视频的所有权利。
如果您喜欢这篇文章/视频,欢迎您捐赠花花。
If you like my articles / videos, donations are welcome.
Be First to Comment