LeetCode 916. Word Subsets

🔗 https://leetcode.com/problems/word-subsets

题目

  • 给两个字符串数组,word1 和 word2
  • 若每一个 word2 中的字符串,都是字符串 x 的 subset,则表示该字符串 x 是 universal 的
  • 返回 word1 中的 universal 的字符串

思路

  • 对 word2 中的每一个字符串,进行 char 的频次统计,取 max
  • 对比 word1 中的字符串,是否可以是 word2 的父集合,若是,则加入 answer

代码

cpp 复制代码
class Solution {
public:
    bool subset(unordered_map<char, int>& m1, unordered_map<char, int>& m2) {
        for (auto pair : m2) {
            char ch = pair.first;
            int cnt = pair.second;
            if (m2[ch] > m1[ch])
                return false;
        }
        return true;
    }

    vector<string> wordSubsets(vector<string>& words1, vector<string>& words2) {
        vector<string> ans;
        unordered_map<char, int> w2;
        for (int i = 0; i < words2.size(); i++) {
            unordered_map<char, int> tmp;
            for (int j = 0; j < words2[i].size(); j++) {
                tmp[words2[i][j]]++;
            }

            for (auto pair : tmp) {
                char ch = pair.first;
                w2[ch] = max(w2[ch], tmp[ch]);
            }
        }

        for (int i = 0; i < words1.size(); i++) {
            unordered_map<char, int> w1;
            for (int j = 0; j < words1[i].size(); j++) {
                w1[words1[i][j]]++;
            }
            if (subset(w1, w2)) {
                ans.push_back(words1[i]);
            }
        }
        return ans;
    }
};
相关推荐
lisw053 小时前
稀疏算法概述!
算法·机器人·无人机
YLCHUP4 小时前
【括号匹配+dp优化】题解:双端括号(brackets)_动态规划_状态优化_数学建模_贪心_性质挖掘_STLmap_C++算法竞赛
数据结构·c++·笔记·算法·数学建模·贪心算法·动态规划
郝学胜-神的一滴5 小时前
Effective STL 条款09:慎重选择删除元素的方法
开发语言·网络·数据结构·c++·算法·stl
geovindu9 小时前
python:Logistic Regression
开发语言·后端·python·算法
geovindu11 小时前
python: Random Forest
开发语言·后端·python·算法·随机森林
凌冰_12 小时前
数据结构 - 线性结构(三)
java·数据结构·算法·软件工程
拂拉氏12 小时前
【知识讲解】 数据结构与算法-树状数组的认识
数据结构·算法·树状数组
饮水桶_T14 小时前
C++ STL00 | 六大核心组件协作框架 笔记
开发语言·算法·百度·facebook·新浪微博
饮水桶_T16 小时前
Java调用大语言模型、多轮对话 笔记
笔记·算法·设计模式·电脑·ai编程
AAA修煤气灶刘哥17 小时前
QQ 音乐怎么在 25 毫秒内,决定一句话该交给谁?
人工智能·算法·llm