Skip to content

Commit

Permalink
[String] Add Solution to Ransom Note
Browse files Browse the repository at this point in the history
  • Loading branch information
Yi Gu committed Aug 25, 2016
1 parent 9263866 commit 0fed05c
Showing 1 changed file with 39 additions and 0 deletions.
39 changes: 39 additions & 0 deletions String/RansomNote.swift
Original file line number Diff line number Diff line change
@@ -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
}
}

0 comments on commit 0fed05c

Please sign in to comment.