Python中字典中最长的单词
假设我们有一个代表英语词典的单词列表,我们必须在给定单词列表中找到最长的单词,该单词可以一次由其他单词组成一个字符。如果可能的答案不止一个,则返回字典顺序最小的最长单词。如果没有答案,则返回空字符串。
因此,如果输入类似于[“h”,“he”,“hel”,“hell”,“hello”]],则输出将为“hello”
为了解决这个问题,我们将遵循以下步骤-
尝试:=新映射
定义一个功能insert()。这将成为事实
现在:=trie
对于单词中的每个c,
now[c]={'#',False},然后
如果c现在不在-
现在:=现在[E]
现在['#']:=真
定义一个功能search()。这将成为事实
现在:=trie
对于单词中的每个c,
返回假
如果现在而不是现在的“#”为“真”,则
现在:=现在[E]
现在返回['#']
对于单词中的每个单词,
呼叫插入(字)
ans:=空字符串
对于单词中的每个单词,
回答:=单词
如果搜索(word)和(word的大小>ans的大小或(word的大小与ans的大小相同并且word<ans的大小)),则
返回ans
让我们看下面的实现以更好地理解-
示例
class Solution:
def longestWord(self, words):
self.trie = {}
def insert(word):
now = self.trie
for c in word:
if c not in now: now[c] = {'#': False}
now = now[c]
now['#'] = True
def search(word):
now = self.trie
for c in word:
if '#' in now and not now['#']: return False
now = now[c]
return now['#']
for word in words:
insert(word)
ans = ""
for word in words:
if (search(word) and (len(word) > len(ans) or (len(word) == len(ans) and word < ans))):
ans = word
return ans
ob = Solution()print(ob.longestWord(["h","he","hel","hell", "hello"]))输入值
["h","he","hel","hell", "hello"]
输出结果
hello