Valid anagram#

Levels: level-1
Data structures: string, hash-table

LeetCode

Description#

  • Given two strings s and t, write a function to determine if t is an anagram of s.

Note:

  • You may assume the string contains only lowercase alphabets.

Examples#

1Input: s = "anagram", t = "nagaram"
2Output: true
1Input: s = "rat", t = "car"
2Output: false

Follow up#

  • What if the inputs contain unicode characters? How would you adapt your solution to such case?

Thinking#

  • This can be solved either by Sorting or hashing.

Python Solution#

 1import collections
 2
 3
 4# Sorting solution
 5def isAnagram(self, s, t):
 6    if len(s) != len(t):
 7        return False
 8    return sorted(s) == sorted(t)
 9
10
11# One liner with using counter
12def isAnagramCounter(self, s, t):
13    return collections.Counter(s) == collections.Counter(t)
14
15
16# using dicts
17def isAnagramDict(self, s, t):
18    dic1, dic2 = [0] * 26, [0] * 26
19    for item in s:
20        dic1[ord(item) - ord('a')] += 1
21    for item in t:
22        dic2[ord(item) - ord('a')] += 1
23    return dic1 == dic2