码迷,mamicode.com
首页 > 其他好文 > 详细

1160.Find Words That Can Be Formed By Characters

时间:2020-03-28 23:19:01      阅读:80      评论:0      收藏:0      [点我收藏+]

标签:tac   字符   建模   哈希   +=   c++   判断   map   you   

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

标签:tac   字符   建模   哈希   +=   c++   判断   map   you   

原文地址:https://www.cnblogs.com/katachi/p/12589846.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!