leetcode-916. Word Subsets(单词子集)

1、题目描述

We are given two arrays A and B of words.  Each word is a string of lowercase letters.

Now, say that word b is a subset of word a if every letter in b occurs in aincluding multiplicity.  For example, "wrr" is a subset of "warrior", but is not a subset of "world".

Now say a word a from A is universal if for every b in Bb is a subset of a

Return a list of all universal words in A.  You can return the words in any order.

2、解题分析

以输入A = ["amazon","apple","facebook","google","leetcode"], B = ["ec","oc","ceo"]为例:

A中单词要满足题目要求,必须满足B中每个词中字符组成的列表包含在该单词中。要满足该要求,该单词需要包含B中所有词中字母的并集(不去重)

但能想到的算法提交都超时了,现在还没有更好的想法...

3、代码

3.1、直接法

1、

# -*- coding: utf-8 -*-
"""
Created on Tue Oct  2 22:49:40 2018

@author: yzp1011
"""
from collections import Counter
import numpy as np
import pandas as pd

class Solution:
    def __init__(self):
        A = ["amazon","apple","facebook","google","leetcode"]
        B = ["ec","oc","ceo"]
        self.wordSubsets(A,B)
        
    def wordSubsets(self, A, B):
        """
        :type A: List[str]
        :type B: List[str]
        :rtype: List[str]
        """
        res = []
        b_df = pd.concat([pd.DataFrame(list(Counter(x).items())).set_index(0) for x in B], axis=1)
        b_df.fillna(0,inplace=True)
        for x in A:
            a_df = pd.DataFrame(list(Counter(x).items())).set_index(0)
            if not a_df.sub(b_df,axis=0,fill_value=0).where(lambda y:y < 0).any().any():
                res.append(x)
        return res


if __name__ == '__main__':
    s = Solution()

2、

# -*- coding: utf-8 -*-
"""
Created on Wed Oct  3 02:09:24 2018

@author: yzp1011
"""
from collections import Counter


class Solution:
    def __init__(self):
        A = ["amazon","apple","facebook","google","leetcode"]
        B = ["ec","oc","ceo"]
        print(self.wordSubsets(A,B))
        
    def wordSubsets(self, A, B):
        """
        :type A: List[str]
        :type B: List[str]
        :rtype: List[str]
        """
        b_dict = [Counter(x) for x in B]
        in_flag = True
        res = []
        for word in A:
            a_dict = Counter(word)
            for b_char_dict in b_dict:
                for k,v in b_char_dict.items():
                    if v > a_dict[k]:
                        in_flag = False
                        break
                if not in_flag:
                    break
            if in_flag:
                res.append(word)
            else:
                in_flag = True
        return res
    

if __name__ == '__main__':
    s = Solution()

3.2、优化算法

# -*- coding: utf-8 -*-
"""
Created on Wed Oct  3 09:47:50 2018

@author: yzp1011
"""
from operator import ior
from functools import reduce
from collections import Counter


class Solution:
    def __init__(self):
        A = ["amazon","apple","facebook","google","leetcode"]
        B = ["ec","oc","ceo"]
        print(self.wordSubsets(A,B))
        
    def wordSubsets(self, A, B):
        """
        :type A: List[str]
        :type B: List[str]
        :rtype: List[str]
        """
        char_b = reduce(ior, map(Counter, B))        
        return [x for x in A if Counter(x) & char_b == char_b]
    

if __name__ == '__main__':
    s = Solution()

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

yzpwslc

您的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值