Topic: Array & Hashing
Soln 1 (dictonary solution):
- Compare the lengths of both strings.
- If they are not the same length, they are not anagrams.
- Create a new dictionary called count.
- Loop through the characters in s:
- If the character already exists in the dictionary, then increment its value by 1.
- Else, assign the value of the key to 1.
- Loop through the characters in t:
- If the character does not exist in the dictionary or the character count is 0, then return False.
- Else, decrement the value of the character by 1.
- Return True.
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
if len(s) != len(t):
return False
count = {}
for char in s:
if char in count:
count[char]+=1
else:
count[char] = 1
for char in t:
if char not in count or count[char] == 0:
return False
count[char]-=1
return True
Soln 2 (set solution):
- Compare the lengths of both strings.
- If they are not the same length, they are not anagrams.
- Loop through the characters in the set of s (set removes the duplicates):
- If the count of any character in s is not equal to the count of the same character in t:
- then return False.
- If all character counts match, then the strings are anagrams (return True).
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
if len(s) != len(t):
return False
for i in set(s):
if s.count(i) != t.count(i):
return False
return True
Soln 3:
A very obvious solution:
- Alphabetically sort both strings (s, t) and compare them. Returns True if they both are the same length and contain the same characters, else False if they do not. (Yes, all on the same line.)
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
return sorted(s) == sorted(t)
Notes:
Sets & dictionaries are unordered and unique, although dictionaries can contain duplicates values
Top comments (0)