From 0fed05c895c2e02c63004d20dff4985d2e4424d9 Mon Sep 17 00:00:00 2001 From: Yi Gu Date: Wed, 24 Aug 2016 23:43:56 -0700 Subject: [PATCH] [String] Add Solution to Ransom Note --- String/RansomNote.swift | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 String/RansomNote.swift diff --git a/String/RansomNote.swift b/String/RansomNote.swift new file mode 100644 index 00000000..b79ca95e --- /dev/null +++ b/String/RansomNote.swift @@ -0,0 +1,39 @@ +/** + * Question Link: https://leetcode.com/problems/ransom-note/ + * Primary idea: Use a dictionary to calculate the existence of characters in magazine + * and check with the ransom Note + * + * Time Complexity: O(n), Space Complexity: O(n) + */ + +class RansomNote { + func canConstruct(ransomNote: String, _ magazine: String) -> Bool { + var magazineMap = _strToMap(magazine) + + for char in ransomNote.characters { + if magazineMap[char] == nil { + return false + } else if magazineMap[char] == 0 { + return false + } else { + magazineMap[char]! -= 1 + } + } + + return true + } + + private func _strToMap(magazine: String) -> [Character: Int] { + var res = [Character: Int]() + + for char in magazine.characters { + if res[char] == nil { + res[char] = 1 + } else { + res[char]! += 1 + } + } + + return res + } +} \ No newline at end of file