Skip to main content

916. Word Subsets

https://leetcode.com/problems/word-subsets/

Python

  • 注意words2裡面可能單一個word有多個character,例如oo如果存在,o的計算其實無關緊要
from collections import Counter, defaultdict


class Solution:
def wordSubsets(self, words1: List[str], words2: List[str]) -> List[str]:
map2 = defaultdict(int)
for word in words2:
for letter, count in Counter(word).items():
map2[letter] = max(map2[letter], count)

result = []
for word in words1:
map1 = Counter(word)
for letter, count in map2.items():
if count > map1.get(letter, 0):
break
else:
result.append(word)
return result