-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path383.py
82 lines (72 loc) · 2.15 KB
/
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
# [ LeetCode ] 383. Ransom Note
def solution(ransomNote: str, magazine: str) -> bool:
characters: dict[str, int] = {}
for character in ransomNote:
if character in characters:
characters[character] += 1
else:
characters[character] = 1
for character in magazine:
if character in characters and characters[character] > 0:
characters[character] -= 1
return True if sum(characters.values()) == 0 else False
def another_solution(ransomNote: str, magazine: str) -> bool:
characters: dict[str, int] = {}
for character in magazine:
if character in characters:
characters[character] += 1
else:
characters[character] = 1
for character in ransomNote:
if character not in characters or characters[character] == 0:
return False
else:
characters[character] -= 1
return True
if __name__ == "__main__":
cases: list[dict[str, dict[str, str] | int]] = [
{
"input": {
"ransomNote": "a",
"magazine": "b"
},
"output": False
},
{
"input": {
"ransomNote": "aa",
"magazine": "ab"
},
"output": False
},
{
"input": {
"ransomNote": "aa",
"magazine": "aab"
},
"output": True
},
{
"input": {
"ransomNote": "aab",
"magazine": "aabb"
},
"output": True
},
{
"input": {
"ransomNote": "aabbc",
"magazine": "aabb"
},
"output": False
}
]
for case in cases:
assert case["output"] == solution(
ransomNote=case["input"]["ransomNote"],
magazine=case["input"]["magazine"]
)
assert case["output"] == another_solution(
ransomNote=case["input"]["ransomNote"],
magazine=case["input"]["magazine"]
)