Ransom Note

Question

Given an arbitrary ransom note string and another string containing letters from all the magazines, write a function that will return true if the ransom note can be constructed from the magazines ; otherwise, it will return false.

Each letter in the magazine string can only be used once in your ransom note.

Note: You may assume that both strings contain only lowercase letters.

canConstruct("a", "b") -> false
canConstruct("aa", "ab") -> false
canConstruct("aa", "aab") -> true

Tags

  • String
  • Hashmap

Thought

Use the dictionary to count the frequency of the character in the ransomNote and compare it with magazine.

Code

class Solution(object):
    def canConstruct(self, ransomNote, magazine):
        """
        :type ransomNote: str
        :type magazine: str
        :rtype: bool
        """
        ch_dict = {}
        for ch in ransomNote:
            if ch not in ch_dict:
                ch_dict[ch] = 1
            else:
                ch_dict[ch] += 1
        for ch in magazine:
            if ch not in ch_dict:
                continue
            else:
                ch_dict[ch] -= 1
                if ch_dict[ch] == 0:
                    del ch_dict[ch]
        return len(ch_dict) == 0

results matching ""

    No results matching ""