题目:有效的字母异位词
给定两个字符串 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