242. Valid Anagram
EasyLeetCodeGiven two strings s and t, return true if t is an anagram of s, and false otherwise.
Example 1
Input: s = "anagram", t = "nagaram"
Output: true
Example 2
Input: s = "rat", t = "car"
Output: false
Constraints
- 1 <= s.length, t.length <= 5 * 104
- s and t consist of lowercase English letters.
How to solve the problem
Code
Approach 1: Hash Table Using Array
Python
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
# Hash Table Using Array
count = [0] * 26
for x in s:
count[ord(x) - ord('a')] += 1
for x in t:
count[ord(x) - ord('a')] -= 1
for res in count:
if res != 0:
return False
return True
Approach 2: Using Counter
Python
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
return Counter(s) == Counter(t)
Complexity
- Time complexity:
- O(n + m)
- O(n)
- Space complexity: O(1)
Comments
No comments yet. Be the first to comment!