242. Valid Anagram
Given two strings
sandt, returntrueiftis an anagram ofs, andfalseotherwise.An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
Example 1:
Input: s = "anagram", t = "nagaram"
Output: trueExample 2:
Input: s = "rat", t = "car"
Output: false
O(n)
def isAnagram(self, s, t):
if len(s) != len(t):
return False
char_map = [0] * 26
for i in range(len(s)):
char_map[ord(s[i]) - ord('a')] += 1
char_map[ord(t[i]) - ord('a')] -= 1
return all(count == 0 for count in char_map)
To know about ord() function.
O(N logN)
def isAnagram(s, t):
if len(s) != len(t):
return False
return sorted(s) == sorted(t)