Level
LeetCode Easy
var countCharacters = function (words, chars) {
  const charsLength = chars.length;
  const arr = Array(26).fill(0);
  let answer = 0;

  for (const char of chars) {
    const charCode = char.charCodeAt() - 97;
    arr[charCode] = ++arr[charCode] || 1;
  }

  for (const word of words) {
    if (word.length > charsLength) continue;

    const tempArr = [...arr];
    let valid = true;
    for (const char of word) {
      const charCode = char.charCodeAt() - 97;

      if (tempArr[charCode]) {
        tempArr[charCode] -= 1;
      } else {
        valid = false;
        break;
      }
    }
    if (valid) answer += word.length;
  }

  return answer;
};

var countCharacters = function (words, chars) {
  const hash = {};
  let answer = 0;

  for (char of chars) {
    hash[char] ? hash[char]++ : (hash[char] = 1);
  }

  words.forEach((word) => {
    const chars = { ...hash };
    for (char of word) {
      if (chars[char]) {
        chars[char]--;
      } else {
        return;
      }
    }
    answer += word.length;
  });

  return answer;
};

var countCharacters = function (words, chars) {
  const map = new Map();
  let answer = 0;

  for (char of chars) {
    map.has(char) ? map.set(char, map.get(char) + 1) : map.set(char, 1);
  }

  words.forEach((word) => {
    const tempMap = new Map(map);
    for (char of word) {
      if (tempMap.get(char)) {
        tempMap.set(char, tempMap.get(char) - 1);
      } else {
        return;
      }
    }
    answer += word.length;
  });

  return answer;
};