-
Notifications
You must be signed in to change notification settings - Fork 0
/
383.赎金信.py
36 lines (31 loc) · 991 Bytes
/
383.赎金信.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# coding=utf-8
"""
@project: Everyday_LeetCode
@Author:Charles
@file: 383.赎金信.py
@date:2023/1/2 21:44
"""
class Solution(object):
def canConstruct(self, ransomNote, magazine):
"""
:type ransomNote: str
:type magazine: str
:rtype: bool
"""
# 核心思想:hash表
# 循环magazine,存储到字典中,key为字母,val字母出现的次数
# 循环ransomNote,当字母在字典中时,且该字母的val不为0,字典中字母的val减一
# 如果字典中有元素都没有找到则返回False
# 都循环完返回True
mag_dict = dict()
for i in magazine:
if i in mag_dict:
mag_dict[i] += 1
else:
mag_dict[i] = 1
for i in ransomNote:
if i in mag_dict and mag_dict[i] != 0:
mag_dict[i] -= 1
else:
return False
return True