LeetCode链接
排序 时间复杂度 O(NlogN)class Solution:
def isAnagram(self, s: str, t: str) -> bool:
return len(s) == len(t) and sorted(s) == sorted(t)
使用 26位的数组 时间复杂度 O(N)
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
if len(s) != len(t):
return False
l = [0] * 26
ordA = ord('a')
for si, ti in zip(s, t):
l[ord(si) - ordA] += 1
l[ord(ti) - ordA] -= 1
return all(i == 0 for i in l)
使用 collections.Counter() 时间复杂度 O(N)
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
if len(s) != len(t):
return False
return collections.Counter(s) == collections.Counter(t)
使用collections.defaultdict()
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
if len(s) != len(t):
return False
dic = collections.defaultdict(int)
for si, ti in zip(s, t):
dic[si] += 1
dic[ti] -= 1
return all(v == 0 for v in dic.values())



