Given two strings s and t, return true if the two strings are anagrams of each other, otherwise return false.
An anagram is a string that contains the exact same characters as another string, but the order of the characters can be different.
Input: s = "racecar", t = "carrace" Output: true
Input: s = "jar", t = "jam" Output: false
Ideally should yield:
O(n+m)
n
is length of s
and m
is length of t
O(1)
Sorting the input strings in alphabetical order, then comparing them as equals.
O(n log n + m log m)
sort
is nominally O(n log n)
.O(n log n + m log m)
O(1)
class Solution: def isAnagram(self, s: str, t: str) -> bool: sortedStr1 = ''.join(sorted(s)) sortedStr2 = ''.join(sorted(t)) if sortedStr2 != sortedStr1: return False return True
class Solution: def isAnagram(self, s: str, t: str) -> bool: if len(s) != len(t): return False str1Ht = {} str2Ht = {} for el in s: if el not in str1Ht: str1Ht[el] = 1 pass str1Ht[el] += 1 for el in t: if el not in str2Ht: str2Ht[el] = 1 pass str2Ht[el] += 1 if str1Ht == str2Ht: return True return False