From LeetCode 383. Ransom Note

Description

Given two strings ransomNote and magazine, return true if ransomNote can be constructed from magazine and falseotherwise.

Each letter in magazine can only be used once in ransomNote.

Solution1: Use counter

class Solution:
    def canConstruct(self, ransomNote: str, magazine: str) -> bool:
        c1 = collections.Counter(ransomNote)
        c2 = collections.Counter(magazine)
        x = c1 - c2
        
        if(len(x)==0):
            return True
        else:
            return False

Solution2: Use list

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

        arr = [0] * 26

        for x in magazine:
            arr[ord(x) - ord('a')] += 1

        for x in ransomNote:
            if arr[ord(x) - ord('a')] == 0:
                return False
            else:
                arr[ord(x) - ord('a')] -= 1
        
        return True