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;
    }
};
相关推荐
许愿与你永世安宁5 分钟前
力扣343 整数拆分
数据结构·算法·leetcode
爱coding的橙子7 分钟前
每日算法刷题Day42 7.5:leetcode前缀和3道题,用时2h
算法·leetcode·职场和发展
满分观察网友z39 分钟前
从一次手滑,我洞悉了用户输入的所有可能性(3330. 找到初始输入字符串 I)
算法
YuTaoShao1 小时前
【LeetCode 热题 100】73. 矩阵置零——(解法二)空间复杂度 O(1)
java·算法·leetcode·矩阵
Heartoxx1 小时前
c语言-指针(数组)练习2
c语言·数据结构·算法
大熊背1 小时前
图像处理专业书籍以及网络资源总结
人工智能·算法·microsoft
满分观察网友z1 小时前
别怕树!一层一层剥开它的心:用BFS/DFS优雅计算层平均值(637. 二叉树的层平均值)
算法
杰克尼2 小时前
1. 两数之和 (leetcode)
数据结构·算法·leetcode
YuTaoShao3 小时前
【LeetCode 热题 100】56. 合并区间——排序+遍历
java·算法·leetcode·职场和发展
二进制person7 小时前
Java SE--方法的使用
java·开发语言·算法