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
相关推荐
Nicole Potter1 小时前
请说明C#中的List是如何扩容的?
开发语言·面试·c#
gu202 小时前
c#编程:学习Linq,重几个简单示例开始
开发语言·学习·c#·linq
不想编程小谭3 小时前
力扣LeetCode: 2506 统计相似字符串对的数目
c++·算法·leetcode
一川风絮千片雪4 小时前
【排版教程】如何在Word/WPS中优雅的插入参考文献
word·wps
杜大哥4 小时前
如何在WPS打开的word、excel文件中,使用AI?
人工智能·word·excel·wps
01_4 小时前
力扣hot100——LRU缓存(面试高频考题)
leetcode·缓存·面试·lru
_Itachi__6 小时前
LeetCode 热题 100 73. 矩阵置零
算法·leetcode·矩阵
青涩小鱼6 小时前
在WPS中设置word的页码不从第一页开始,从指定页开始插入页码
word·wps
夏末秋也凉6 小时前
力扣-贪心-376 摆动序列
算法·leetcode
pchmi7 小时前
CNN常用卷积核
深度学习·神经网络·机器学习·cnn·c#