leetcode - 916. Word Subsets

Description

You are given two string arrays words1 and words2.

A string b is a subset of string a if every letter in b occurs in a including multiplicity.

For example, "wrr" is a subset of "warrior" but is not a subset of "world".

A string a from words1 is universal if for every string b in words2, b is a subset of a.

Return an array of all the universal strings in words1. You may return the answer in any order.

Example 1:

复制代码
Input: words1 = ["amazon","apple","facebook","google","leetcode"], words2 = ["e","o"]
Output: ["facebook","google","leetcode"]

Example 2:

复制代码
Input: words1 = ["amazon","apple","facebook","google","leetcode"], words2 = ["l","e"]
Output: ["apple","google","leetcode"]

Constraints:

复制代码
1 <= words1.length, words2.length <= 10^4
1 <= words1[i].length, words2[i].length <= 10
words1[i] and words2[i] consist only of lowercase English letters.
All the strings of words1 are unique.

Solution

A little bit tricky and one take-away is: if the total time complexity is around 1 0 8 10^8 108, don't try it, it will be TLE.

The core idea is, we build a hashmap of words2, and iterate all the strings in words1 to decide if we want to select it. The tricky part is how we build the hash map.

Because oo won't be a subset of aeiou, but ['ao', 'eo'] would be a subset of aeiou, so to build the hash map, we just need to store the maximum frequency of the string in words2.

Time complexity: o ( w o r d s 2. l e n + w o r d s 1. l e n ) o(words2.len + words1.len) o(words2.len+words1.len)

Space complexity: o ( 1 ) o(1) o(1)

Code

python3 复制代码
class Solution:
    def wordSubsets(self, words1: List[str], words2: List[str]) -> List[str]:
        words2_fre = [0] * 26
        for each_word in words2:
            ch_cnt = collections.Counter(each_word)
            for each_ch, each_cnt in ch_cnt.items():
                ch_index = ord(each_ch) - ord('a')
                words2_fre[ch_index] = max(words2_fre[ch_index], each_cnt)
        res = []
        for each_word in words1:
            ch_cnt = collections.Counter(each_word)
            is_candidate = True
            for i in range(26):
                if ch_cnt.get(chr(i + ord('a')), 0) < words2_fre[i]:
                    is_candidate = False
                    break
            if is_candidate:
                res.append(each_word)
        return res
相关推荐
OPEN-F24 分钟前
Python进阶教程:自动化办公实战
python·c#·自动化
czhc11400756631 小时前
C# 处理体数据:装、钉、交、取消
c#
淡海水2 小时前
03-03-线性-LinkedList-T-源码不变式与选择边界
windows·链表·c#·编译·linkedlist·clr·机器码
AI英德西牛仔2 小时前
秘塔 导出word指令之外:AI导出鸭电脑版的底层逻辑与批量交付哲学
人工智能·word·excel·deepseek·ai导出鸭
evans在进步2 小时前
LeetCode 53 最大子数组和:一次遍历掌握 Kadane 算法
算法·leetcode·职场和发展
Nil2083 小时前
leetcode 230二叉搜索树中第k小的元素
算法·leetcode·职场和发展
旖旎夜光3 小时前
LeetCode 69:x 的平方根(二分查找) —— 题解
数据结构·c++·算法·leetcode·二分查找
学习星球3 小时前
【LeetCode算法题精讲】图算法精讲——从图遍历到拓扑排序
数据结构·算法·leetcode·图搜索
2601_963906783 小时前
[特殊字符] DocxTableExport:一键提取 Word 文档中的表格数据
word·软件需求
yivifu3 小时前
解决word文档中行尾中文破折号被分断的问题
word