Given two strings ransomNote and magazine, return true if ransomNote can be constructed by using the letters from magazine and false otherwise.
Each letter in magazine can only be used once in ransomNote.
Example 1:Input: ransomNote = “a”, magazine = “b” Output: false
Example 2:Input: ransomNote = “aa”, magazine = “ab” Output: false
Example 3:Input: ransomNote = “aa”, magazine = “aab” Output: true
Constraints:
1 <= ransomNote.length, magazine.length <= 105ransomNoteandmagazineconsist of lowercase English letters.
It’s easy to use hashmap to record how many times that each character has appeared in magazine, and loop through ransomNote check. However, this way might be slow since I didn’t leverage any Python built-in collections.
class Solution:
def canConstruct(self, ransomNote: str, magazine: str) -> bool:
check_dict = {}
for character in magazine:
if check_dict.get(character) is None:
check_dict[character] = 1
else:
check_dict[character] += 1
for character in ransomNote:
char_count = check_dict.get(character)
if char_count is None or char_count == 0:
return False
else:
check_dict[character] -= 1
return True
If we can leverage Counter class from collections, then it will be easy and clean.
To check more about Counter from here: https://docs.python.org/3/library/collections.html#collections.Counter
class Solution:
def canConstruct(self, ransomNote: str, magazine: str) -> bool:
a = Counter(ransomNote)
b = Counter(magazine)
return a & b == a
搶先發佈留言