题目在这:https://leetcode-cn.com/problems/valid-anagram/
思路分析:
可以建立两个哈希表,key存字母,val存出现过的次数。
最后比较两个 哈希表就行了。
完整代码
def isAnagram(self, s: str, t: str) -> bool:
hashmap_s = {}
hashmap_t = {}
for i in s:
if i not in hashmap_s:
hashmap_s[i] = 1
else:
hashmap_s[i] += 1
for j in t:
if j not in hashmap_t:
hashmap_t[j] = 1
else:
hashmap_t[j] += 1
if hashmap_s == hashmap_t:
return True
else:
return False
哈希表直接的比较:
key值和val值都是一样的,才算两个哈希表相等。
颠倒key和val值,则不相等。 比如 {1:2,3:4} 和{2:1.3:4}
两个哈希表中的 顺序不一样,算相等。 比如 {1:2,3:4} 和{3:4,1:2}