[LeetCode] 1160. Find Words That Can Be Formed by Characters

Easy

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. 1 <= words.length <= 1000
  2. 1 <= words[i].length, chars.length <= 100
  3. All strings contain lowercase English letters only.

题目大意:如果一个字符串可以用chars中存在的字母组成(字母不可重复使用),那么称这个字符串是好的。

对于输入的words和字符串chars,求出words中所有好的字符串的长度之和。

 

看到这道题我就想到了map,使用map来记录字符串中字母出现的次数。用一个map记录chars中各字母出现的次数,再用另一map记录words中字符串的字母出现情况。

比较两个map中指定字母的出现次数就可判断出字符串是否符合要求,如果words的map中某个字母的出现次数>chars的map中该字母的出现次数,那么这个字符串不符合要求。

代码如下:

class Solution {
public:
    int countCharacters(vector<string>& words, string chars) {
        int res=0;
        
        map<char,int> c;
        for(int i=0;i<chars.size();++i){
            c[chars[i]]+=1;
        }
        
        for(string word:words){
            map<char,int> w;
            for(char c:word){
                w[c]+=1;
            }
            
            map<char,int>::iterator it;
            for(it=w.begin();it != w.end();++it){
                if(it->second>c[it->first]){
                    break;
                }
            }
            if(it==w.end())res+=word.size();
        }
        return res;
    }
};

代码稍微改进一下,把单词字母出现次数记录和对比放在一起:

class Solution {
public:
    int countCharacters(vector<string>& words, string chars) {
        int res=0;
        
        map<char,int> c;
        for(int i=0;i<chars.size();++i){
            c[chars[i]]+=1;
        }
        
        for(string word:words){
            map<char,int> w;
            int flag=0;
            for(char cc:word){
                w[cc]+=1;
                if(w[cc]>c[cc]){
                    flag=1;
                    break;
                }
            }
            if(!flag)res+=word.size();
        }
        return res;
    }
};

 

posted @ 2019-09-03 18:03  程嘿嘿  阅读(457)  评论(0编辑  收藏  举报