1. 程式人生 > >[LeetCode] 916. 單詞子集

[LeetCode] 916. 單詞子集

題目

我們給出兩個單詞陣列 AB。每個單詞都是一串小寫字母。

現在,如果 b 中的每個字母都出現在 a 中,包括重複出現的字母,那麼稱單詞 b 是單詞 a 的子集。 例如,“wrr” 是 “warrior” 的子集,但不是 “world” 的子集。

如果對 B 中的每一個單詞 bb 都是 a 的子集,那麼我們稱 A 中的單詞 a 是通用的。

你可以按任意順序以列表形式返回 A 中所有的通用單詞。

示例 1:
輸入:A = ["amazon","apple","facebook","google","leetcode"], B = ["e","o"]
輸出:["facebook","google","leetcode"]
示例 2:
輸入:A = ["amazon","apple","facebook","google","leetcode"], B = ["l","e"]
輸出:["apple","google","leetcode"]
示例 3:
輸入:A = ["amazon","apple","facebook","google","leetcode"], B = ["e","oo"]
輸出:["facebook","google"]
示例 4:
輸入:A = ["amazon","apple","facebook","google","leetcode"], B = ["lo","eo"]
輸出:["google","leetcode"]
示例 5:
輸入:A = ["amazon","apple","facebook","google","leetcode"], B = ["ec","oc","ceo"]
輸出:["facebook","leetcode"]

思路

本題要求 對 B 中的每一個單詞 b,b 都是 a 的子集。那麼b中某一個字母出現幾次,在a中也至少要有幾次。對於多個b,某一單詞出現的次數取最多的一次。

對於所有的b,採用一個雜湊陣列Bhash統計每個字母出現的次數。對單個b,通過雜湊陣列bhash統計在這個單詞中每個字母出現的次數。在統計完後與總陣列Bhash進行比對,保留較大的值。

當所有b遍歷完後獲得最終的Bhash

,與每一個a的雜湊陣列進行比對即可。

Python程式碼

class Solution:
def wordSubsets(self, A, B):
    """
    :type A: List[str]
    :type B: List[str]
    :rtype: List[str]
    """
    Bhash = {}
    
    for str in B:
        bhash = {} 
        for s in str:
            if not s in bhash:
                bhash[s] = 1
            else: bhash[s] +=1
        for i in bhash:
            if not i in Bhash:
                Bhash[i] = bhash[i]
            else : Bhash[i] = max(Bhash[i],bhash[i])
            
    res = []
    for str in A:
        ahash = {}
        flag = 1
        for s in str:
            if not s in ahash:
                ahash[s] = 1
            else: ahash[s] +=1
        for i in Bhash:
            if not i in ahash:
                flag = 0
                break
            elif ahash[i] < Bhash[i]:
                flag = 0
                break
        if flag == 0:
            continue
        else :
            res.append(str)
    return res