1160.Find Words That Can Be Formed By Characters

Posted katachi

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了1160.Find Words That Can Be Formed By Characters相关的知识,希望对你有一定的参考价值。

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.

 

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:

1 <= words.length <= 1000
1 <= words[i].length, chars.length <= 100
All strings contain lowercase English letters only.

常规题目,记下来主要是为了提醒自己。
一是审题,一开始认为是chars里面的字母对于所有word只能使用一次,结果是一个word只能使用一次。
二是实现,思路都是map,但是提交后看别人的,恍然大悟。原来可以自己构造哈希表。也不是什么稀罕的思路,只是遇到这个问题时自己没想到。
为什么?还不是建模的角度,对问题思考的深度。只有26种字母这点被忽略带来的就是我的执行时间是900+ms

class Solution {
public:
    int countCharacters(vector<string>& words, string chars) {
        map<char,int> charsMap;
        int howmany=0;
        for (int i=0;i<chars.size();i++)
            if (charsMap.find(chars[i])==charsMap.end()) 
                charsMap[chars[i]]=1;
            else
                charsMap[chars[i]]++;
        for (auto it=words.begin();it!=words.end();it++){
            map<char,int> wordsMap;
            for (int i=0;i<(*it).size();i++)
                if (wordsMap.find((*it)[i])==wordsMap.end())
                    wordsMap[(*it)[i]]=1;
                else    
                    wordsMap[(*it)[i]]++;
            bool isContain=true;
            int tmpCnt=0;
            for (auto t=wordsMap.begin();t!=wordsMap.end();t++){
                if (charsMap.find(t->first)==charsMap.end() ||
                    charsMap[t->first] < t->second){
                        isContain=false;
                        break;
                    }
                else
                    tmpCnt+=t->second;
            }
            if (isContain)
                howmany+=tmpCnt;
        }
        return howmany;
    }
};

只谈思路,和两数之和差??不多。把chars存入一个哈希表,然后对于words中的每个word,判断其字符是不是都在表中。
值得一提的是某word中的某字母可能多次出现,所以要考虑到这点。由于思路局限性,我的实现把word的每个字母也存入哈希表,
所以Can Be Formed的条件是word中每个字母个数都<相应chars中字母的个数。

好像到现在还从来没看过题目下面的Note?

以上是关于1160.Find Words That Can Be Formed By Characters的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode --- 1160. Find Words That Can Be Formed by Characters 解题报告

Leetcode 1160. Find Words That Can Be Formed by Characters

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

Pronunciation Changes in Words that are Both Nouns and Verbs

1222. Queens That Can Attack the King

MySQL 1091 can‘t drop check that column/key exists