Easy
Valid Anagram — Python
Full explanation · Time O(n) · Space O(1)
# Time: O(n)
# Space: O(1)
import collections
class Solution(object):
def isAnagram(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
if len(s) != len(t):
return False
count = collections.defaultdict(int)
for c in s:
count[c] += 1
for c in t:
count[c] -= 1
if count[c] < 0:
return False
return True
# Time: O(n)
# Space: O(1)
class Solution2(object):
def isAnagram(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
return collections.Counter(s) == collections.Counter(t)
# Time: O(nlogn)
# Space: O(n)
class Solution3(object):
def isAnagram(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
return sorted(s) == sorted(t)