Solution 1
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
if len(s) != len(t):
return False
s = list(s)
t = list(t)
s.sort()
t.sort()
for i in range(len(s)):
if s[i] != t[i]: return False
return True
Time complexity is O(nlogn). Space complexity is O(n).
Solution 2
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
return sorted(s) == sorted(t)
Time complexity is O(nlogn). Space complexity is O(n).
Solution 3
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
if len(s) != len(t):
return False
dic1, dic2 = [0]*26, [0]*26
for i in range(len(s)):
dic1[ord(s[i]) - ord('a')] += 1
dic2[ord(t[i]) - ord('a')] += 1
return dic1 == dic2
Time complexity is O(n). Space complexity is O(1).