假设我们有一个单词列表和一个称为字母的字符串,我们必须找到可以通过重新排列给定字母而得到的最长单词的大小。字母中可能有星号(*),它可以匹配任何字符。并且没有必要使用所有字母。
因此,如果输入像单词= [“ prince”,“ rice”,“ price”,“ limit”,“ hello”]字母=“ * r ** ce *”,则输出将为6,因为我们可以做的最长单词是“prince”,长度为6。
让我们看下面的实现以更好地理解:
from collections import Counter class Solution: def solve(self, words, letters): has = Counter(letters) def valid(s): need = Counter(s) extra = sum([max(0, need[char] - has[char]) for char in need]) return extra <= has["*"] return max([len(word) for word in words if valid(word)]) ob = Solution()words = ["prince", "rice", "price", "limit", "hello"] letters = "*r**ce*" print(ob.solve(words, letters))
["prince", "rice", "price", "limit", "hello"], "*r**ce*"
输出结果
6