May Leetcode Challenge - Day 3

Problem

Ransom Note

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

Solution

Use hashtable to count number of appearance of each character.
Decrease the count of each character whenever found it in magazine.
Finally, if hashtable is empty, we can tell possible to build ransom note

class Solution {
    func canConstruct(_ ransomNote: String, _ magazine: String) -> Bool {
        var dict = [Character: Int]()
        
        for c in ransomNote {
            dict[c] = (dict[c] ?? 0) + 1
        }
        
        for c in magazine {
            if let val = dict[c] {
                if val - 1 == 0 {
                    dict[c] = nil
                }else {
                    dict[c] = val - 1
                }
            }
            
            if dict.isEmpty { return true }
        }
        
        return dict.isEmpty
    }
}