Leetcode
242. Valid Anagram
Leeter
2021. 11. 6. 11:26
Description:
Given two strings s and t, return true if t is an anagram of s, and false otherwise.
'''
[1] sort)
idea::
1. sort both s and t
2. check s[i]==t[i]
code::
def isAnagram(self, s: str, t: str) -> bool:
if len(s)!=len(t):
return False
s_list=sorted(s)
t_list=sorted(t)
for i in range(len(s_list)):
if s_list[i]!=t_list[i]:
return False
return True
-T/C: O(nlogn + mlogm) # n==len(s), m==len(t)
-S/C: O(m+n)
'''
'''
[2] hashmap)
code::
def isAnagram(self, s: str, t: str) -> bool:
if len(s)!=len(t):
return False
smap={}
tmap={}
for c in s:
if c in smap:
smap[c]+=1
else:
smap[c]=1
for c in t:
if c in tmap:
tmap[c]+=1
else:
tmap[c]=1
for c,val in smap.items():
if not c in tmap or val!=tmap[c]:
return False
return True
-T/C: O(m+n)
-S/C: O(m+n)
'''
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
if len(s)!=len(t):
return False
smap={}
tmap={}
for c in s:
if c in smap:
smap[c]+=1
else:
smap[c]=1
for c in t:
if c in tmap:
tmap[c]+=1
else:
tmap[c]=1
for c,val in smap.items():
if not c in tmap or val!=tmap[c]:
return False
return True