跳至主要內容

Leetcode 383. Ransom Note

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

Constraints:

  • 1 <= ransomNote.length, magazine.length <= 105
  • ransomNote and magazine consist of lowercase English letters.

It’s easy to use hashmap to record how many times that each character has appeared in magazine, and loop through ransomNote check. However, this way might be slow since I didn’t leverage any Python built-in collections.

class Solution:
    def canConstruct(self, ransomNote: str, magazine: str) -> bool:
        check_dict = {}

        for character in magazine:
            if check_dict.get(character) is None:
                check_dict[character] = 1
            else:
                check_dict[character] += 1

        for character in ransomNote:
            char_count = check_dict.get(character)

            if char_count is None or char_count == 0:
                return False
            else:
                check_dict[character] -= 1
        
        return True

If we can leverage Counter class from collections, then it will be easy and clean.

To check more about Counter from here: https://docs.python.org/3/library/collections.html#collections.Counter

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

        return a & b == a
分類:HashmapLeetcode

搶先發佈留言

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *

由 Compete Themes 設計的 Author 佈景主題