[LeetCode] 1160. Find Words That Can Be Formed by Characters 拼写单词 (统计字母数量的常用方法)

题目:


 思路:

思路很简单,只要分别统计chars中和每个单词中字母出现的个数,chars中的字母大于等于每个单词中的字母的个数,这个单词便是good

可以利用C++中的map实现,现在记录一种更灵活更常用的方式,凡是要统计字母个数,都可以这样处理:

创建一个数组vec[26],每个位置分别存储的是26个字母中对应字母的个数,以 char - 'a'  的方式得到字母的索引

代码:

class Solution {
public:
    vector<int> getV(string strings){
        vector<int> res(26);
        for(char str: strings){
            res[str - 'a']++;
        }
        return res;
    }
    int countCharacters(vector<string>& words, string chars) {
        vector<int> vec = getV(chars);
        vector<int> cur;
        int res=0;
        for(string word: words){
            cur = getV(word);
            int i;
            for(i=0; i<26; i++){
                if(cur[i] > vec[i]) break;
            }
            if(i == 26) res+=word.size();
        }
        return res;
    }
};
原文地址:https://www.cnblogs.com/ech2o/p/12513935.html