【Leetcode_easy】1160. Find Words That Can Be Formed by Characters

problem

1160. Find Words That Can Be Formed by Characters

solution

class Solution {
public:
    int countCharacters(vector<string>& words, string chars) {
        int res = 0;
        unordered_map<char, int> charmap;
        for(auto ch:chars) charmap[ch]++;
        for(auto word:words)
        {
            unordered_map<char, int> tmp = charmap;
            bool match = true;
            for(auto ch:word) 
            {
                if(tmp[ch]>0) tmp[ch]--;//err...why count dont work...
                else { match = false; break; }
            }
            if(match) res += word.size();
        }
        return res;
    }/*
    int countCharacters(vector<string>& words, string chars) {
        int res = 0;
        vector<int> charcnt(26);
        for(auto ch:chars) charcnt[ch-'a']++;
        for(auto word:words)
        {
            vector<int> tmp = charcnt;
            bool match = true;
            for(auto ch:word) 
            {
                if(tmp[ch-'a']>0) tmp[ch-'a']--;//pay attention to index.
                else { match = false; break; }
            }
            if(match) res += word.size();
        }
        return res;
    }
*/
};

 

参考

1. Leetcode_easy_1160. Find Words That Can Be Formed by Characters;

posted on 2019-08-29 17:49  鹅要长大  阅读(145)  评论(0编辑  收藏  举报

导航