zoukankan      html  css  js  c++  java
  • 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?

  • 相关阅读:
    background-size ie8及以下不兼容的解决方案
    前端
    JavaScript ES(6-11)
    前端工程化
    前端安全漏洞与防范
    Vue源码思维导图
    项目流程总结
    typescript版数据结构与算法库
    tsconfig.json各项配置注解
    Sql server动态加载存储过程--分页
  • 原文地址:https://www.cnblogs.com/katachi/p/12589846.html
Copyright © 2011-2022 走看看