Skip to main content

赎金信

Tips

题目类型: HashMap

题目

给你两个字符串: ransomNotemagazine, 判断 ransomNote 能不能由 magazine 里面的字符构成.

如果可以, 返回 true; 否则返回 false.

magazine 中的每个字符只能在 ransomNote 中使用一次.

提示:
  • 1 <= ransomNote.length, magazine.length <= 10⁵
  • ransomNotemagazine 由小写英文字母组成
示例
输入: ransomNote = "a", magazine = "b"
输出: false
输入: ransomNote = "aa", magazine = "ab"
输出: false
输入: ransomNote = "aa", magazine = "aab"
输出: true

题解

/**
* @param {string} ransomNote
* @param {string} magazine
* @return {boolean}
*/
var canConstruct = function (ransomNote, magazine) {
const map = new Map()
for (const ch of ransomNote) {
map.set(ch, map.has(ch) ? map.get(ch) + 1 : 1)
}

for (const ch of magazine) {
if (map.has(ch)) {
if (map.get(ch) > 1) {
map.set(ch, map.get(ch) - 1)
} else {
map.delete(ch)
}
}
}

return map.size === 0
}