leetcode1160. 拼写单词

给你一份『词汇表』(字符串数组) words 和一张『字母表』(字符串) chars。

假如你可以用 chars 中的『字母』(字符)拼写出 words 中的某个『单词』(字符串),那么我们就认为你掌握了这个单词。

注意:每次拼写时,chars 中的每个字母都只能用一次。

返回词汇表 words 中你掌握的所有单词的 长度之和。

示例 1:

输入:words = ["cat","bt","hat","tree"], chars = "atach"
输出:6
解释: 
可以形成字符串 "cat""hat",所以答案是 3 + 3 = 6

示例 2:

输入:words = ["hello","world","leetcode"], chars = "welldonehoneyr"
输出:10
解释:
可以形成字符串 "hello""world",所以答案是 5 + 5 = 10

提示:

  • 1 <= words.length <= 1000
  • 1 <= words[i].length, chars.length <= 100
  • 所有字符串中都仅包含小写英文字母

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/find-words-that-can-be-formed-by-characters
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

完整代码

基本思想:
查找每一个单词中的每一个字母是否在字母表中出现,由于字母表中的字母不允许重复出现,所以在查找到该字母时,将该字母删掉。

class Solution {
public:
    int countCharacters(vector<string>& words, string chars) {
        if(words.size() == 0 || chars.size() == 0)
            return 0;
        int res = 0;
        for(int i = 0; i < words.size(); ++i){
            string temp = chars;
            bool flag = false;
            for(int j = 0; j < words[i].size(); ++j){
                int pos = temp.find(words[i][j]);
                if(pos < 0 || pos >= temp.size()){
                    flag = true;
                    break;
                }
                temp.erase(pos, 1);
            }
            if(!flag)
                res += words[i].size();
        }
        return res;
    }
};

解法二:参考别人的想法
统计字母表中每个单词的每个字母出现的次数,统计每个单词中每个字母出现的次数,如果每个单词中的每个字母出现的次数小于等于字母表中的每个字母出现的次数,那么该单词可以拼写
注意:这里可以用map,unordered_map实现,也可以用长度为26的整型数组实现,因为题目中明确说明了所有字符串中都仅包含小写英文字母

class Solution {
public:
    int countCharacters(vector<string>& words, string chars) {
        if(words.size() == 0 || chars.size() == 0)
            return 0;
        int res = 0;
        //1.统计字母表中的每个字母出现的次数。
        vector<int> count(26, 0);
        for(auto c : chars)
            ++count[c - 'a'];
        for(auto word : words){
            vector<int> temp(26, 0);
            for(auto c : word)
                ++temp[c - 'a'];
            bool flag = false;
            for(int i = 0; i < 26; ++i){
                if(temp[i] > count[i]){
                    flag = true;
                    break;
                }
            }
            if(!flag)
                res += word.size();
        }
        return res;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章