LeetCode: 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.

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

Solution

首先建立ㄧ個空的 Hash,命名為 rh。 接著用 String 所提供 each_char方法逐個地記錄字元資訊(key 是字母, value是出現的次數)。

如果 rh[i] 所代表的字元次數超過 magazine 所含有的字元次數,就回傳 false。 Ransom note 跑完每個字元之後,沒有回傳 false 就代表 magazine 足夠提供 ransom note 所需要每個字元。

def can_construct(ransom_note, magazine)
  rh = Hash.new(0)
  ransom_note.each_char do |i|
    rh[i] += 1
    if rh[i] > magazine.count(i)
      return false
    end
  end
  return true
end