383.Ransom Note
Given an arbitrary ransom note string and another string containing letters from all the magazines, write a function that will return true if the ransom note can be constructed from the magazines ; otherwise, it will return false.
Each letter in the magazine string can only be used once in your ransom note.
Note:
You may assume that both strings contain only lowercase letters.
canConstruct("a", "b") -> false
canConstruct("aa", "ab") -> false
canConstruct("aa", "aab") -> true
Submissions
- golang
func canConstruct(ransomNote string, magazine string) bool {
save := make(map[rune]int)
for _,char := range magazine{
if _, ok := save[char]; ok{
save[char] += 1
}else{
save[char] = 1
}
}
for _,char := range ransomNote{
if _, ok := save[char]; ok && save[char] > 0{
save[char] -= 1
}else{
return false
}
}
return true
}
- scala
object Solution {
def canConstruct(ransomNote: String, magazine: String): Boolean = {
if (magazine.size < ransomNote.size) return false
val Array(map1, map2) = Array(ransomNote, magazine).map(_.toCharArray.groupBy(identity).mapValues(_.size))
if (!(map1.keySet subsetOf map2.keySet)) return false
map2.transform((k, v) => v - map1.getOrElse(k, 0)).filter(_._2 < 0).size <= 0
}
}