描述
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
Note:
1 <= s.length <= 50000
s.length == t.length
s and t contain lower-case English letters only.
解析
根据题意,要想使 t 变为 s 的 Anagram ,只需要字符一样就行了,所以最小的步数就是将 t 和 s 中的出现的字符都计数,然后以 s 为基准进行遍历,对字符及其数量进行比较,按以下算法累加即可得出最小步数,具体代码。
解答
class Solution(object):
def minSteps(self, s, t):
"""
:type s: str
:type t: str
:rtype: int
"""
S = collections.Counter(s)
T = collections.Counter(t)
count = 0
for key in S.keys():
if key not in T:
count += S[key]
elif key in T and S[key]>T[key]:
count += S[key]-T[key]
return count
运行结果
Runtime: 444 ms, faster than 43.46% of Python online submissions.
Memory Usage: 14.2 MB, less than 37.55% of Python online submissions.
解析
根据题意,想要求最小的步数,遍历 s 字符串,将存在于 t 中的字符都用空字符替换,每次只能替换一个字符,剩下的 t 字符串的长度即为结果。
解答
class Solution(object):
def minSteps(self, s, t):
"""
:type s: str
:type t: str
:rtype: int
"""
for c in s:
t = t.replace(c,'',1)
return len(t)
运行结果
Runtime: 3264 ms, faster than 5.07% of Python online submissions.
Memory Usage: 13.8 MB, less than 60.76% of Python online submissions.
每日格言:人生最大遗憾莫过于错误坚持和轻易放弃