Suppose we have a list of words and a string called letters, we have to find the size of the longest word that can be made by rearranging the given letters. In the letters there may be asterisk character (*) it can match any character. And it is not necessary to use all the letters.
So, if the input is like words = ["prince", "rice", "price", "limit", "hello"] letters = "*r**ce*", then the output will be 6, as the longest word we can make is "prince" the length is 6.
To solve this, we will follow these steps:
Let us see the following implementation to get better understanding:
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