242:
242题目不难,主要是判断一下两个单词中每个字母的出现字数, 用一个数组来表示一下即可,但是里面使用到的一些函数需要记忆一下:
1.ord(i):用于获取字符的 ASCII(或 Unicode)码值
ord('a') # 返回 97
ord('b') # 返回 98
ord('z') # 返回 122
2.还可用于此题的Counter和defaultdict
Counter 可以直接统计可迭代对象中各元素的出现次数。
from collections import Counter
def isAnagram(self, s: str, t: str) -> bool:
return Counter(s) == Counter(t)
Counter("anagram")返回类似:{'a': 3, 'n': 1, 'g': 1, 'r': 1, 'm': 1}
两个 Counter 对象相等,当且仅当:
- 它们包含完全相同的键(元素);
- 每个键对应的计数值(value)也完全相同;
- 不关心元素的顺序或插入顺序;
- 计数值为 0 的键会被自动忽略(因为
Counter不存储值为 0 的键)。
defaultdict 是一个字典,访问不存在的键时会自动创建默认值(比如 int 默认为 0)。
from collections import defaultdict
def isAnagram(self, s: str, t: str) -> bool:
if len(s) != len(t):
return False
count = defaultdict(int)
for ch in s:
count[ch] += 1
for ch in t:
count[ch] -= 1
if count[ch] < 0: # 提前剪枝(可选)
return False
return all(v == 0 for v in count.values())
349:
本题的思路不难,就是先用一个数组生成一个所有出现过的元素的集合,然后再用另一个数组去与集合比对看是否有相同元素,有则加入返回的列表中,只是在细节上需要注意,当一个元素被检测到出现过以后,后续应该删除该元素防止重复返回的列表中重复出现,但是该问题也好解决,即让返回的列表先由一个集合来表示,最后要返回时将集合转化列表即可:
class Solution:
def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
table={}
for num in nums1:
table[num]=table.get(num,0) +1
res =set ()
for num in nums2:
if num in table:
res.add(num)
return list(res)
注意的操作:
1.对于字典的操作table[num]=1是对一个字典对的副职,而table.get(num,0)则是寻找字典中key为num的值,若没有则返回默认值,该处是0。
2.res={1,2,3}是集合,但是res={}是字典
有效字母异位词与数组交集

被折叠的 条评论
为什么被折叠?



