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;
    }
};
相关推荐
CS创新实验室7 分钟前
计算机考研之数据结构:P 问题和 NP 问题
数据结构·考研·算法
OTWOL37 分钟前
【C++编程入门基础(一)】
c++·算法
谏君之43 分钟前
C语言实现的常见算法示例
c语言·算法·排序算法
机器视觉知识推荐、就业指导1 小时前
【数字图像处理二】图像增强与空域处理
图像处理·人工智能·经验分享·算法·计算机视觉
IT猿手2 小时前
超多目标优化:基于导航变量的多目标粒子群优化算法(NMOPSO)的无人机三维路径规划,MATLAB代码
人工智能·算法·机器学习·matlab·无人机
Erik_LinX2 小时前
算法日记25:01背包(DFS->记忆化搜索->倒叙DP->顺序DP->空间优化)
算法·深度优先
Alidme3 小时前
cs106x-lecture14(Autumn 2017)-SPL实现
c++·学习·算法·codestepbystep·cs106x
小王努力学编程3 小时前
【算法与数据结构】单调队列
数据结构·c++·学习·算法·leetcode
最遥远的瞬间3 小时前
15-贪心算法
算法·贪心算法
维齐洛波奇特利(male)3 小时前
(动态规划 完全背包 **)leetcode279完全平方数
算法·动态规划