原題鏈接
1160. 拼寫單詞
解題思路
- 用Map緩存chars中所有字母的數量
- 遍歷單詞的所有字母
- 如果Map中存在當前字母,就將Map緩存的字母數量減一
- 如果Map中不存在當前字母,或者字母數量為0,表示chars中的字母無法拼寫單詞,退出循環(huán)
- 如果能完成該單詞所有字母的遍歷,表示chars中的字母可以拼寫單詞,可以統計該單詞的長度
/**
* @param {string[]} words
* @param {string} chars
* @return {number}
*/
var countCharacters = function(words, chars) {
// 緩存結果
let sum = 0
// 緩存chars中所有字母的數量
const charMap = new Map()
// 統計chars中所有字母的數量
for (const char of chars) {
charMap.set(char, (charMap.get(char) ?? 0) + 1)
}
// 為外部循環(huán)設置標簽,便于直接退出
outer:
for (const word of words) {
// 創(chuàng)建一個新Map,用于統計chars的字母使用情況
const map = new Map(charMap)
// 遍歷word中的所有字母
for (const char of word) {
// 如果char在map中不存在,表示chars無法拼寫該單詞,退出outer循環(huán)
if (!map.get(char)) {
continue outer
}
// 當前字母被使用,數量減一
map.set(char, map.get(char) - 1)
}
// 如果字母都被使用,表示chars可以拼寫出單詞,則將單詞長度計入sum
sum += word.length
}
// sum為words中所有可被chars拼寫出的單詞長度
return sum
};