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;
    }
};
相关推荐
Dola_Zou1 小时前
工厂智能排产软件算法保护与按产线计费实战
算法·自动化·软件工程·软件加密
啦啦啦啦啦zzzz3 小时前
Logger的组装(c++20)
c++·算法·c++20
尾善爱看海4 小时前
前端算法与手写题集
前端·算法
程序员阿鹏4 小时前
为什么MySQL InnoDB选择B+树?
数据结构·数据库·b树·sql·mysql·算法·缓存
AI 思录5 小时前
Prompt 事故档案(八):日常表达被标为“待校准”,AI 的爹味语法从哪里来
大数据·人工智能·算法·prompt·用户体验·ai合规
月光船幽幽5 小时前
跨范式映射的稳定接口设计
人工智能·python·算法
2601_965742226 小时前
全媒体运营与短视频代运营,两者有什么区别?
大数据·数据结构·人工智能·算法·ai·媒体
我血条子呢7 小时前
前端解析word方案
前端·word
HUIBUR科技7 小时前
业务数据一键写入 Word 文档,稳定不跑版的免费方案 FormDocx
word
wordbaby7 小时前
混合检索:两全其美的艺术
人工智能·算法