Sort
Sorted, anagrams must be identical.
Time: , space:
.
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
if len(s) != len(t):
return False
return all(a == b for a, b in zip(sorted(s), sorted(t)))
Character map
Every character of t must appear in s possibly in different order.
Time: , space:
.
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
if len(s) != len(t):
return False
s_map = {}
for c in s:
s_map[c] = s_map.get(c, 0) + 1
for c in t:
if s_map.get(c, 0) == 0:
return False
s_map[c] -= 1
return True
Leave a comment