def isAnagram1(self, s, t):
dic1, dic2 = {}, {}
for item in s:
dic1[item] = dic1.get(item, 0) + 1
for item in t:
dic2[item] = dic2.get(item, 0) + 1
return dic1 == dic2
def isAnagram2(self, s, t):
dic1, dic2 = [0]*26, [0]*26
for item in s:
dic1[ord(item)ord('a')] += 1
for item in t:
dic2[ord(item)ord('a')] += 1
return dic1 == dic2
def isAnagram3(self, s, t):
return sorted(s) == sorted(t)
Python solutions (sort and dictionary).


@caikehe : Good solution. Just a small suggestion to your code.
I instead of writing two for loops for s and t each, we can write in a single loop.
'''
if len(s) != len(t) :
return False
dict1 = [0]*26
dict2 = [0] * 26
for i in range(len(s)) :
dict1[ord(s[i])ord('a')] += 1
dict2[ord(t[i])  ord('a')] += 1
return dict1 == dict2
'''


@caikehe yes,I like your solutions ,and this is my oneline code:
return collections.Counter(s)==collections.Counter(t)

Beats 97.5%
def isAnagram(self, s, t): return all([s.count(c)==t.count(c) for c in string.ascii_lowercase])
Using defaultdict beats 97%
def isAnagram(self, s, t): 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