forked from NilaakashSingh/LeetCode-Swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
RansomNote.swift
39 lines (33 loc) · 1.03 KB
/
RansomNote.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
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
}
}