字典模拟哈希表计数器
Leetcode 242: 有效的字母异位词(python)
注:本人文章中内容中来自于各大佬的经验总结,仅供自身复习及学习,并无商业用途,若有时忘记标注作者及出处还请提醒,敬请见谅。
字典模拟哈希表创建两个字典,分别用于存储两个字符串中每个字符出现的次数,最后对两个字典的键和值依次进行比较。
class Solution: def isAnagram(self, s: str, t: str) -> bool: dic1 = {} dic2 = {} for e in s: if e in dic1: dic1[e] += 1 else: dic1[e] = 1 for e in t: if e in dic2: dic2[e] += 1 else: dic2[e] = 1 if len(dic1) != len(dic2): return False for key in dic1: if (key not in dic2) or (dic1.get(key) != dic2.get(key)): return False return True计数器
突然发现python中一个强大的存在:计数器(Counter)!
它的作用和我上面用字典的方法本质是一样的,但是简洁方便!
class Solution: def isAnagram(self, s: str, t: str) -> bool: return Counter(s) == Counter(t) 作者:bluegreenred 链接:https://leetcode-cn.com/problems/valid-anagram/solution/242-you-xiao-de-zi-mu-yi-wei-ci-python-h-pjsc/ 来源:力扣(LeetCode) 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)