1160. Find Words That Can Be Formed by Characters(Leetcode每日一题-2020.03.17)

Problem

You are given an array of strings words and a string chars.

A string is good if it can be formed by characters from chars (each character can only be used once).

Return the sum of lengths of all good strings in words.

Example1

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.

Example2

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.

Solution

class Solution {
public:
    int countCharacters(vector<string>& words, string chars) {
        if(words.empty() || chars.empty())
            return 0;
        unordered_map<char,int> chars_hash_table;
        convertStr2HashTable(chars,chars_hash_table);

        int ret = 0;

        for(auto &word:words)
        {
            unordered_map<char,int> word_hash_table;
            convertStr2HashTable(word,word_hash_table);

            bool valid = true;
            for(unordered_map<char,int>::const_iterator it = word_hash_table.begin();it != word_hash_table.end();++it)
            {
                if(chars_hash_table.find(it->first) == chars_hash_table.end() || chars_hash_table.find(it->first)->second < it->second)
                {
                    valid = false;
                    break;
                }
            }

            if(valid)
                ret += word.length();
        }

        return ret;
    }

    void convertStr2HashTable(string &str,unordered_map<char,int> &hash_table)
    {
        for(auto c: str)
        {
           
            ++hash_table[c];
        }

    }
};
发布了496 篇原创文章 · 获赞 215 · 访问量 53万+

猜你喜欢

转载自blog.csdn.net/sjt091110317/article/details/104929531