383. 赎金信
方法一:哈希表
var canConstruct = function(ransomNote, magazine) {
const strArr = new Array(26).fill(0), base = "a".charCodeAt();
for (const s of magazine) {
strArr[s.charCodeAt() - base]++;
}
for (const s of ransomNote) {
const index = s.charCodeAt() - base;
if (!strArr[index]) return false;
strArr[index]--;
}
return true;
};
方法二:字符统计
var canConstruct = function(ransomNote, magazine) {
if (ransomNote.length > magazine.length) {
return false;
}
const cnt = new Array(26).fill(0);
for (const c of magazine) {
cnt[c.charCodeAt() - 'a'.charCodeAt()]++;
}
for (const c of ransomNote) {
cnt[c.charCodeAt() - 'a'.charCodeAt()]--;
if(cnt[c.charCodeAt() - 'a'.charCodeAt()] < 0) {
return false;
}
}
return true;
};
方法三:暴力解法
var canConstruct = function(ransomNote, magazine) {
for (let i = 0; i < magazine.length; i++) {
for (let j = 0; j < ransomNote.length; j++) {
if (magazine[i] === ransomNote[j]) {
ransomNote.splice(ransomNote[j], 1);
}
}
}
if (ransomNote.length === 0) {
return true;
console.log("magazine的字符可以组成ransomNote");
}
return false;
console.log("magazine的字符不可以组成ransomNote");
};
let a = canConstruct(["a", "a", "c"], ["a", "a", "b", "c"]);
console.log(a);