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;
    }
};
相关推荐
JeffersonZU2 小时前
【数据结构】1-4算法的空间复杂度
c语言·数据结构·算法
L_cl2 小时前
【Python 算法零基础 4.排序 ① 选择排序】
数据结构·算法·排序算法
山北雨夜漫步3 小时前
机器学习 Day18 Support Vector Machine ——最优美的机器学习算法
人工智能·算法·机器学习
拼好饭和她皆失3 小时前
算法加训之最短路 上(dijkstra算法)
算法
瓦力wow5 小时前
c语言 写一个五子棋
c语言·c++·算法
X-future4265 小时前
院校机试刷题第六天:1134矩阵翻转、1052学生成绩管理、1409对称矩阵
线性代数·算法·矩阵
Codeking__6 小时前
前缀和——中心数组下标
数据结构·算法
爱喝热水的呀哈喽6 小时前
非线性1无修
算法
課代表6 小时前
Office 中 VBE 的共同特点与区别
word·excel·vba·office·vbe
花火QWQ6 小时前
图论模板(部分)
c语言·数据结构·c++·算法·图论