有关哈希表的LeetCode做题笔记,Python实现
242. 有效的字母异位词 Valid Anagram
第一种方法:对两个字符串排序后对比
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
return sorted(s) == sorted(t)
第二种方法:用哈希表对字符串内每个字符计数,最后比对哈希表,这里用dict实现
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
map1, map2 = {}, {}
for i in s:
map1[i] = map1.get(i, 0) + 1
for j in t:
map2[j] = map2.get(j, 0) + 1
return map1 == map2
网友评论