给你一份『词汇表』(字符串数组) words 和一张『字母表』(字符串) chars。

假如你可以用 chars 中的『字母』(字符)拼写出 words 中的某个『单词』(字符串),那么我们就认为你掌握了这个单词。

注意:每次拼写(指拼写词汇表中的一个单词)时,chars 中的每个字母都只能用一次。

返回词汇表 words 中你掌握的所有单词的 长度之和。

示例 1:

  1. 输入:words = ["cat","bt","hat","tree"], chars = "atach"
  2. 输出:6
  3. 解释:
  4. 可以形成字符串 "cat" "hat",所以答案是 3 + 3 = 6

题解

数组的做法就比较简单的, 直接通过多次对比就能得出结果,唯一注意的是,map比Object快了好多。。

/**
 * @param {string[]} words
 * @param {string} chars
 * @return {number}
 */
var countCharacters = function(words, chars) {
    const map = new Map();
    let max = 0;
    for (char of chars) {
        map.set(char, (map.get(char) || 0) + 1);
    }
    for (word of words) {
        const temp = new Map();
        let m = 0;
        for (str of word) {
            if (map.has(str)) {
                temp.set(str, (temp.get(str) || 0) + 1);
                if (temp.get(str) <= map.get(str)) {
                    m++;
                }
            }
        }
        if (m === word.length) {
            max += m;
        }
    }
    return max;
};