Valid Anagram
242. Valid Anagram
Difficulty: Easy
Related Topics: Hash Table, String, Sorting
Given two strings s and t, return true if t is an anagram of s, and false otherwise.
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: true
Example 2:
Input: s = “rat”, t = “car” Output: false
Code:
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
if len(s) != len(t):
return False
sdict={}
tdict={}
for i in s:
if i in sdict:
sdict[i]+=1
else:
sdict[i]=1
for i in t:
if i in tdict:
tdict[i]+=1
else:
tdict[i]=1
if sdict != tdict:
return False
else:
return True
Feedbacks:
I created two dictionaries to store keys and values of two string and compared two dictionary to check if they are anagram or not.