720. 词典中最长的单词
题目链接 | 720. 词典中最长的单词 |
---|---|
思路 | Trie树的经典应用 |
题解链接 | 官方题解 |
关键点 | 构建Trie树 |
时间复杂度 | |
空间复杂度 |
代码实现:
class Trie: def __init__(self): self.children = [None] * 26 self.isEnd = False def insert(self, word): node = self for ch in word: ch = ord(ch) - ord("a") if not node.children[ch]: node.children[ch] = Trie() node = node.children[ch] node.isEnd = True def search(self, word): node = self for ch in word: ch = ord(ch) - ord("a") if node.children[ch] is None or not node.children[ch].isEnd: return False node = node.children[ch] return True class Solution: def longestWord(self, words: List[str]) -> str: tree = Trie() for word in words: tree.insert(word) answer = "" for word in words: if tree.search(word) and ( len(word) > len(answer) or len(word) == len(answer) and word < answer ): answer = word return answer
分类:
LeetCode
标签:
LeetCode-Trie
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
· SQL Server 2025 AI相关能力初探
· 为什么 退出登录 或 修改密码 无法使 token 失效