242. 有效的字母异位词

本文探讨了四种不同的Python实现方法来检查两个字符串是否为字母异位词,包括循环删除法、集合计数、字典Counter()以及排序法。尽管前两种方法性能不佳,但通过使用字典Counter()和排序法,显著提高了执行速度和内存效率。这些算法对于字符串操作和算法优化具有重要意义。
摘要由CSDN通过智能技术生成

242. 有效的字母异位词

法一:循环删除法

性能极差

执行用时: 2040 ms , 在所有 Python3 提交中击败了 5.18% 的用户
内存消耗: 16 MB , 在所有 Python3 提交中击败了 5.01% 的用户

class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
        s=list(s)
        t=list(t)
        for i in s:
            flag=False
            for j in range(len(t)):
                if i==t[j]:
                    del t[j]
                    flag=True
                    break
            if flag==False:
                return False
        if not t:
            return True
        else:
            return False

法二:set统计次数

性能依然很差

执行用时: 96 ms , 在所有 Python3 提交中击败了 5.86% 的用户
内存消耗:15.5 MB , 在所有 Python3 提交中击败了25.15% 的用户

class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
        s=list(s)
        t=list(t)
        setss=set(s)
        settt=set(t)
        cyc=setss if setss>settt else settt
        for i in cyc:
            if s.count(i)!=t.count(i):
                return False
        return True

法三:字典Counter()

性能一般

执行用时: 52 ms , 在所有 Python3 提交中击败了 83.74% 的用户
内存消耗:15.4 MB , 在所有 Python3 提交中击败了 31.53% 的用户

class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
        s=Counter(list(s))
        t=Counter(list(t))
        if s!=t:
            return False
        return True

执行用时: 64 ms , 在所有 Python3 提交中击败了46.07% 的用户
内存消耗:15.3 MB , 在所有 Python3 提交中击败了33.75% 的用户

class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
        d=Counter(list(s))
        for i in range(len(t)):
            d[t[i]]=d.get(t[i],0)-1
        for i in d:
            if d[i]!=0:
                return False
        return True

法五:排序

执行用时: 56 ms , 在所有 Python3 提交中击败了 74.09% 的用户
内存消耗: 15.4 MB , 在所有 Python3 提交中击败了 32.76% 的用户

s=list(s)
t=list(t)
s.sort()
t.sort()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值