Tcdian / keep

今天不想做,所以才去做。
MIT License
5 stars 1 forks source link

1160. Find Words That Can Be Formed by Characters #71

Open Tcdian opened 4 years ago

Tcdian commented 4 years ago

1160. Find Words That Can Be Formed by Characters

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

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

注意:每次拼写时,chars 中的每个字母都只能用一次。

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

Example 1

Input: words = ["cat","bt","hat","tree"], chars = "atach"
Output: 6
Explanation: 
The strings that can be formed are "cat" and "hat" so the answer is 3 + 3 = 6.

Example 2

Input: words = ["hello","world","leetcode"], chars = "welldonehoneyr"
Output: 10
Explanation: 
The strings that can be formed are "hello" and "world" so the answer is 5 + 5 = 10.

Note

Tcdian commented 4 years ago

Solution

/**
 * @param {string[]} words
 * @param {string} chars
 * @return {number}
 */
var countCharacters = function(words, chars) {
    let result = 0;
    const charsMap = new Array(26).fill(0);

    for (let i = 0; i < chars.length; i++) {
        charsMap[chars.charCodeAt(i) - 97] += 1;
    }

    words.forEach((word) => {
        const wordMap = new Array(26).fill(0);
        let isGoodString = true;

        for (let i = 0; i < word.length; i++) {
            wordMap[word.charCodeAt(i) - 97] += 1;
        }

        for (let i = 0; i < 26; i++) {
            if (charsMap[i] < wordMap[i]) {
                isGoodString = false;
                break;
            }
        }

        if (isGoodString) {
            result += word.length;
        }
    });

    return result;
};