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.
大意:每個magazine的字符只能用一次,是否可以拼湊出ransom note
思路:
這個題用哈希表可以很簡單的解決,先遍歷magazine,將字符的出現次數儲存在哈希表中,再遍歷ransom note,將用掉的字符次數減掉,用完就刪除,如果在哈希表中找不到可以用的字符就return false
var canConstruct = function(ransomNote, magazine) {
const record = new Map();
for (const word of magazine) {
if (!record.has(word)) {
record.set(word, 1);
} else {
record.set(word, record.get(word) + 1);
}
}
for (const word of ransomNote) {
if (!record.has(word)) {
return false;
} else {
const num = record.get(word);
if (num > 1) {
record.set(word, num - 1);
} else {
record.delete(word);
}
}
}
return true;
};
或是直接用charCodeAt取ascii存到數組裡,就不需要哈希表
var canConstruct = function(ransomNote, magazine) {
// 只有小寫字母,所以數組初始26個0
const arr = new Array(26).fill(0);
for (const word of magazine) {
// 'a'的ascii = 97
arr[word.charCodeAt() - 97] += 1;
}
for (const word of ransomNote) {
// 賦值語句會返回賦的值,所以可以直接判斷返回值是不是 < 0
if ((arr[word.charCodeAt() - 97] -= 1) < 0) {
return false;
}
}
return true;
};
原本以為直接操作數組省去查找會快一點,但寫完發現沒有XD
上面是數組,下面是哈希表~