哈希
解题思路
字符串 magazine 的每一个字符存储在哈希表中,并 计数 +1;
字符串 ransomNote 的字符在哈希表中出现一次,则 计数 -1;
最后遍历哈希表,若有值小于 0 返回 false,否则返回 true;
复杂度
-
时间复杂度:
O(n)
,其中 n 为 s 的长度; -
空间复杂度:
O(n)
,其中 n 为 s 的长度;
代码实现
var canConstruct = function (ransomNote, magazine) {
if (magazine.length < ransomNote.length) return false;
const hash = new Array(26).fill(0);
const offset = 97;
for (let i = 0; i < magazine.length; i++) {
hash[magazine.charCodeAt(i) - offset]++;
}
for (let i = 0; i < ransomNote.length; i++) {
if (hash[ransomNote.charCodeAt(i) - offset] > 0) {
hash[ransomNote.charCodeAt(i) - offset]--;
} else {
return false;
}
}
return true;
};
参考资料
leetcode🧑💻 852. 山脉数组的峰顶索引
上一篇