拼写单词 给你一份『词汇表』(字符串数组) words 和一张『字母表』(字符串) chars。 假如你可以用 chars 中的『字母』(字符)拼写出 words 中的某个『单词』(字符

力扣1160. 拼写单词
给你一份『词汇表』(字符串数组) words 和一张『字母表』(字符串) chars。

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

注意:每次拼写(指拼写词汇表中的一个单词)时,chars 中的每个字母都只能用一次。

返回词汇表 words 中你掌握的所有单词的 长度之和。
力扣原题传送
示例:

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

击败截图 ↓
击败截图
言归正传,本题而言我使用了哈希法,将字母作为哈希表的key值,若单一将value部分用一个int类型空间来记录chars每个字母出现的次数在后续每个字符串比较时需要反复遍历chars字符串更新该值,因此我采用的是使用pair容器;

其中,first部分记录对应字母在chars字符串中出现的次数
second部分记录比较过程中该字符串所需该字母的数目

认真考虑一番这样的存储是换来了时间效率的,因为在后续更新second 的值时只需简单的置0,不再进行对chars字符串遍历。
在这里插入图片描述
代码如下:

class Solution {
    
    
public:
    int countCharacters(vector<string>& words, string chars) {
    
    
         int count = 0;
        int n = words.size(), cl = chars.length();//n记录数组长度,cl记录char字符长
        unordered_map<char,pair<int,int>> hash;//key值存放字母,pair 存chars各自母的数量以及words中字母的数量
        for (int i = 0; i < cl; i++) {
    
    
            unordered_map<char, pair<int, int>>::iterator it = hash.find(chars[i]);
            if (it == hash.end())
                hash[chars[i]] = make_pair(1, 0);
            else {
    
    
                (it->second).first++;//计数各字母数量
            }
        }//哈希创建完毕

        for (int i = 0; i < n; i++) {
    
    
            for (unordered_map<char, pair<int, int>>::iterator it = hash.begin(); it != hash.end(); it++)
            {
    
    
                if (it->second.second != 0)
                    it->second.second = 0;//清空上个单词的内容
            }
            int j = 0;
            for (; j < words[i].length(); j++) {
    
    
                unordered_map<char, pair<int, int>>::iterator it = hash.find(words[i][j]);
                if (it == hash.end())//没找到字母,跳出
                    break;
                else {
    
    
                    if (++(it->second).second > it->second.first)//字母不够使用,跳出
                        break;
                }
               
            }
     if (j >= words[i].length())//循环正常结束
                    count += words[i].length();
        }
        return count;
    }
};

猜你喜欢

转载自blog.csdn.net/Genius_bin/article/details/113090605