Skip to content

Commit c0fcd1c

Browse files
committed
D. J.:
- Added leetcode problem and solution for 383 Ransom Note
1 parent aedaf89 commit c0fcd1c

File tree

3 files changed

+46
-0
lines changed

3 files changed

+46
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ This repository contains awesome LeetCode problems and solutions written in Pyth
1515
- [125 Valid Palindrome](https://leetcode.com/problems/valid-palindrome/description/)
1616
- [169 Majority Element](https://leetcode.com/problems/majority-element/description/)
1717
- [189 Rotate Array](https://leetcode.com/problems/rotate-array/description/)
18+
- [383 Ransom Note](https://leetcode.com/problems/ransom-note/description/)
1819
- [392 Is Subsequence](https://leetcode.com/problems/is-subsequence/description/)
1920

2021
## Development 🔧
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
class Solution:
2+
def canConstruct(self, ransomNote: str, magazine: str) -> bool:
3+
"""
4+
Given two strings ransomNote and magazine, return true if ransomNote can be constructed
5+
by using the letters from magazine and false otherwise.
6+
7+
Each letter in magazine can only be used once in ransomNote.
8+
"""
9+
# Count letters from ransomNote
10+
counter_r = {}
11+
for s in ransomNote:
12+
if s not in counter_r:
13+
counter_r[s] = 1
14+
else:
15+
counter_r[s] += 1
16+
17+
# Count letters from magazine
18+
counter_m = {}
19+
for s in magazine:
20+
if s not in counter_m:
21+
counter_m[s] = 1
22+
else:
23+
counter_m[s] += 1
24+
25+
# Compare both counts
26+
for k in counter_r:
27+
if k not in counter_m or counter_r[k] > counter_m[k]:
28+
return False
29+
return True

tests/test_383_ransom_note.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
import pytest
2+
3+
from awesome_python_leetcode._383_ransom_note import Solution
4+
5+
6+
@pytest.mark.parametrize(
7+
argnames=["ransomNote", "magazine", "expected"],
8+
argvalues=[
9+
("a", "b", False),
10+
("aa", "ab", False),
11+
("aa", "aab", True),
12+
],
13+
)
14+
def test_func(ransomNote: str, magazine: str, expected: bool):
15+
can_construct = Solution().canConstruct(ransomNote, magazine)
16+
assert can_construct == expected

0 commit comments

Comments
 (0)