(Leetcode) 有效的字母异位词 - Python实现

题目:有效的字母异位词
给定两个字符串 s 和 t ,编写一个函数来判断 t 是否是 s 的字母异位词。
示例 :
输入: s = "anagram", t = "nagaram",输出: true
输入: s = "rat", t = "car",输出: false
说明:
你可以假设字符串只包含小写字母。
进阶:
如果输入字符串包含 unicode 字符怎么办?你能否调整你的解法来应对这种情况?

-----------------------------------------------------------------------------

解法1:通过Python自带的 collections() 来实现。

class Solution(object):
    def isAnagram(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: bool
        """
 
        if len(s) != len(t):
            return False

        import collections

        # 分别将2个字符串转换为字典格式 :{字符:词频}
        dic1 = collections.Counter(s)
        dic2 = collections.Counter(t)

        for key in dic1.keys():
            if key not in dic2.keys() or dic1[key] != dic2[key]:
                return False
        return True

解法2:直接通过字典 dict 来处理,该方法跟collections类似。

class Solution(object):
    def isAnagram(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: bool
        """

        if len(s) != len(t):
            return False
        dic1 = {}
        dic2 = {}
        for i in range(len(s)):
            if s[i] not in dic1:
                dic1[s[i]] = 1
            else:
                dic1[s[i]] += 1
        for j in range(len(t)):
            if t[j] not in dic2:
                dic2[t[j]] = 1
            else:
                dic2[t[j]] += 1

        for key in dic1.keys():
            if key not in dic2.keys() or dic1[key] != dic2[key]:
                return False
        return True

解法3:通过 sorted() 方法实现。

sorted() 函数对所有 可迭代的对象  进行排序操作。

sort 与 sorted 区别:

sort 是应用在 list 上的方法,sorted 可以对所有 "可迭代的对象" 进行排序操作。

list 的 sort 方法返回的是对已经存在的列表进行操作,无返回值,而内建函数 sorted 方法返回的是一个新的 list,而不是在原来的基础上进行的操作。

class Solution(object):
    def isAnagram(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: bool
        """

        return sorted(s) == sorted(t)

解法4:通过set() + count() 组合巧妙实现

class Solution(object):
    def isAnagram(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: bool
        """
        
        if len(t) != len(s):
            return False

        # 对t进行set() 去重
        c = set(t)
        for i in c:
            if t.count(i) != s.count(i):
                return False
        return True

解法5:通过all()函数实现。可以算是解法4的优雅升级版

all() 函数用于判断给定的可迭代参数 iterable 中的所有元素是否都为 TRUE,如果是返回 True,否则返回 False。

元素除了是 0、空、None、False 外都算 True。all() 函数等价于:

def all(iterable):
    for element in iterable:
        if not element:
            return False
    return True
class Solution(object):
    def isAnagram(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: bool
        """
        
        return len(s) == len(t) and all([s.count(i) == t.count(i) for i in set(s)])

参考

https://www.runoob.com/python/python-func-all.html

https://www.runoob.com/python/python-func-sorted.html

https://www.cnblogs.com/MartinLwx/p/9204386.html

https://blog.csdn.net/qiubingcsdn/article/details/82904133

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值