Python solutions (sort and dictionary).

• ``````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)``````

• should consider the case: when s or t is None?

• just need one dict

• another implementation of dict-based approach with builtin Counter

``````def isAnagram1(self, s, t):
return collections.Counter(s) == collections.Counter(t)``````

• If using sorted(), we can use it like this:

``````class Solution(object):
def isAnagram(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
sorted_s = "".join(sorted(s))
sorted_t = "".join(sorted(t))

return sorted_s == sorted_t``````

• list is okay.

``````class Solution(object):
def isAnagram(self, s, t):
ls = list(s)
ls.sort()

lt = list(t)
lt.sort()

return lt == ls
``````

• really like the first method the way you wrote. thanks

• This post is deleted!

• ``````    def isAnagram(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
import collections
d=collections.defaultdict(int)
str1=s+t
for i in xrange(len(s)+len(t)):
if i<len(s):
d[str1[i]]+=1
else:
d[str1[i]]-=1
return all(x==0 for x in d.values())
``````

Works well too!

• @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
'''

• @qeatzy What is the time complexity for Counter(s)?

• This post is deleted!

• @caikehe yes,I like your solutions ,and this is my one-line 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
``````

• @qeatzy I did this one. Super slow.... `sorted` is a little better, just a little....

• This post is deleted!

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.