Ai
1 Star 2 Fork 5

LilithSangreal/LeetCode-Solutions

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
longest-word-in-dictionary.py 885 Bytes
一键复制 编辑 原始数据 按行查看 历史
Sanghee Kim 提交于 2019-01-29 01:45 +08:00 . update longest-word-in-dictionary.py
# Time: O(n), n is the total sum of the lengths of words
# Space: O(t), t is the number of nodes in trie
from collections import defaultdict
from operator import getitem
class Solution(object):
def longestWord(self, words):
"""
:type words: List[str]
:rtype: str
"""
_trie = lambda: defaultdict(_trie)
trie = _trie()
for i, word in enumerate(words):
reduce(getitem, word, trie)["_end"] = i
# DFS
stack = trie.values()
result = ""
while stack:
curr = stack.pop()
if "_end" in curr:
word = words[curr["_end"]]
if len(word) > len(result) or (len(word) == len(result) and word < result):
result = word
stack += [curr[letter] for letter in curr if letter != "_end"]
return result
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/LilithSangreal/LeetCode-Solutions.git
git@gitee.com:LilithSangreal/LeetCode-Solutions.git
LilithSangreal
LeetCode-Solutions
LeetCode-Solutions
master

搜索帮助