Problem
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.
Algorithm
Use a list save the letters in “magazine” and remove the letters in ransomNote.
Code
class Solution:
def canConstruct(self, ransomNote: str, magazine: str) -> bool:
magazineCnts = [0] * 26
for c in magazine:
magazineCnts[ord(c) - ord('a')] += 1
for c in ransomNote:
if magazineCnts[ord(c) - ord('a')] > 0:
magazineCnts[ord(c) - ord('a')] -= 1
else:
return False
return True