less than 1 minute read

383. Ransom Note

Difficulty: Easy

Related Topics: Hash Table, String, Counting

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

Code:

class Solution:
    def canConstruct(self, ransomNote: str, magazine: str) -> bool:
        magdict = {}
        for i in magazine:
            if i in magdict:
                magdict[i] += 1
            else:
                magdict[i] = 1
        for i in ransomNote:
            if i in magdict:
                magdict[i]-=1
                if magdict[i] < 0:
                    return False
            else:
                return False
        return True

Feedbacks:

I first create a dictionary to store keys and values of magazine. And as I loop through the ransomNote string, I decrease one as I meet a character in magazine dictionary. Else, I return False, because it means that there’s no such character in magazine.