Python程式:查詢由給定字母組成的最長單詞的長度
假設我們有一系列單詞和一個名為letters的字串,我們需要找到透過重新排列給定字母可以組成的最長單詞的長度。在letters中可能包含星號字元(*),它可以匹配任何字元。並且不需要使用所有字母。
因此,如果輸入類似於words = ["prince", "rice", "price", "limit", "hello"] letters = "*r**ce*",則輸出將為6,因為我們可以組成的最長單詞是“prince”,長度為6。
為了解決這個問題,我們將遵循以下步驟
- has := 一個包含letters中每個元素的字母和頻率的對映
- 定義一個函式valid()。它將接收s
- need := 一個包含s中每個元素的字母和頻率的對映
- extra := (對於need中的所有字元,計算need[char] - has[char] 的最大值(0和need[char] - has[char]中的較大值)之和
- 當extra <= has["*"]時返回true
- 從主方法執行以下操作
- 返回列表中所有元素的最大值:[當單詞有效時,所有單詞中單詞的長度]
讓我們看看以下實現,以便更好地理解
示例
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
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP