383. Ransom Note

Easy
​
Given two strings ransomNote and magazine, return true if ransomNote can be constructed by using the letters from magazine and false otherwise.
Each letter in magazine can only be used once in ransomNote.
Example 1:
Input: ransomNote = "a", magazine = "b"
Output:
false
Example 2:
Input: ransomNote = "aa", magazine = "ab"
Output:
false
Example 3:
Input: ransomNote = "aa", magazine = "aab"
Output:
true
Constraints:
  • 1 <= ransomNote.length, magazine.length <= 105
  • ransomNote and magazine consist of lowercase English letters.

解題

Runtime: 23 ms, faster than 50.05%
Memory Usage: 3.9 MB, less than 83.60%
func canConstruct(ransomNote string, magazine string) bool {
m := make(map[byte]int)
for i := 0; i < len(magazine); i++ {
m[magazine[i]]++
}
for i := 0; i < len(ransomNote); i++ {
if m[ransomNote[i]] == 0 { return false }
m[ransomNote[i]]--
}
return true
}