跳转至

1160.拼写单词 (Easy)*

题目描述*

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

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

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

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

提示*

1 <= words.length <= 1000, 1 <= words[i].length, chars.length <= 100

所有字符串中都仅包含小写英文字母

代码*

class Solution {
public:
    int countCharacters(vector<string>& words, string chars) {
        vector<int> freq(26, 0);
        for(auto c : chars) {
            freq[c - 'a']++;
        }
        int res = 0;
        bool ifSpell = true;
        for(auto word : words) {
            auto tmp = freq;
            for(auto c : word) {
                if(--tmp[c - 'a'] < 0) {
                    ifSpell = false;
                    break;
                }
            }
            res += (ifSpell ? word.length() : 0);
            ifSpell = true;
        }
        return res;
    }
};

最后更新: July 23, 2022