LeetCode题解(0648):单词替换(Python)
发布日期:2021-06-29 20:09:27 浏览次数:3 分类:技术文章

本文共 798 字,大约阅读时间需要 2 分钟。

题目:(中等)

标签:字典树、哈希表

解法 时间复杂度 空间复杂度 执行用时
Ans 1 (Python) ( D + S ) (D+S) (D+S) O ( D ) O(D) O(D) 56ms (97.96%)
Ans 2 (Python)
Ans 3 (Python)

解法一(字典树):

class Solution:    def replaceWords(self, dictionary: List[str], sentence: str) -> str:        root = {
} for word in dictionary: now = root for ch in word: if ch not in now: now[ch] = {
} now = now[ch] now["@"] = None def replace(w): n = root for i, c in enumerate(w): if "@" in n: return w[:i] if c not in n: return w else: n = n[c] return w return " ".join(replace(word) for word in sentence.split(" "))

转载地址:https://dataartist.blog.csdn.net/article/details/109836807 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:LeetCode题解(0676):实现一个魔法字典(Python)
下一篇:LeetCode题解(0624):数组列表中的最大距离(Python)

发表评论

最新留言

哈哈,博客排版真的漂亮呢~
[***.90.31.176]2024年04月26日 07时06分27秒