Skip to main content

383. Ransom Note

https://leetcode.com/problems/ransom-note/

Python

Mapped by 26 letter list

class Solution:
def canConstruct(self, ransomNote: str, magazine: str) -> bool:
used = list(magazine)

for char in ransomNote:
if char not in used:
return False
used[used.index(char)] = None

return True

Built-in Counter

from collections import Counter


class Solution:
def canConstruct(self, ransomNote: str, magazine: str) -> bool:
counts = Counter(magazine)

for letter in ransomNote:
if letter not in counts or counts[letter]-1 < 0:
return False
counts[letter] -= 1

return True