Skip to content

Commit

Permalink
Merge pull request soapyigu#107 from soapyigu/String
Browse files Browse the repository at this point in the history
[String] Add Solution to Ransom Note
  • Loading branch information
soapyigu authored Aug 25, 2016
2 parents 845406f + 0fed05c commit 4a16739
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 4a16739

Please sign in to comment.