leetcode 1347. Minimum Number of Steps to Make Two Strings Anagram(python)

描述

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.

每日格言:人生最大遗憾莫过于错误坚持和轻易放弃

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

王大丫丫

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值