forked from soapyigu/LeetCode-Swift
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
[String] Add Solution to Ransom Note
- Loading branch information
Yi Gu
committed
Aug 25, 2016
1 parent
9263866
commit 0fed05c
Showing
1 changed file
with
39 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} | ||
} |