Leetcode: 383. Ransom Note
- Primary idea: Matching character frequencies between 2 string
- Time Complexity: O(m + n)
- Space Complexity: O(n)
func countCharacterFrequency(_ string: String) -> [Character: Int] {
var frequencyDict: [Character: Int] = [:]
for char in string {
frequencyDict[char, default: 0] += 1
}
return frequencyDict
}
func canConstruct(_ ransomNote: String, _ magazine: String) -> Bool {
guard magazine.count >= ransomNote.count else { return false }
var f = countCharacterFrequency(magazine)
for c in ransomNote {
if f[c] == nil {
return false
}
if f[c] == 0 {
return false
}
f[c] = f[c]! - 1
}
return true
}
canConstruct("a", "b") // false
canConstruct("aa", "ab") // false
canConstruct("aa", "aab") // true