题目
实现一个 Trie (前缀树),包含 insert, search, 和 startsWith 这三个操作。
示例:
Trie trie = new Trie();trie.insert("apple");trie.search("apple"); // 返回 truetrie.search("app"); // 返回 falsetrie.startsWith("app"); // 返回 truetrie.insert("app");trie.search("app"); // 返回 true
说明:
- 可以假设所有的输入都是由小写字母
a-z构成的。 - 保证所有输入均为非空字符串。
方案一(数组)
class Node:def __init__(self, val):self.val = valself.is_word = False # 是否是一个词self.children = [None] * 26class Trie:def __init__(self):"""Initialize your data structure here."""self.root = Node(None)def insert(self, word: str) -> None:"""Inserts a word into the trie."""nodes = self.root.childrenlength = len(word)for i, c in enumerate(word):index = ord(c) - 97 # ord('a') == 97if not nodes[index]:nodes[index] = Node(c)if i == length - 1:nodes[index].is_word = Truenodes = nodes[index].childrendef search(self, word: str) -> bool:"""Returns if the word is in the trie."""nodes = self.root.childrenlength = len(word)for i, c in enumerate(word):index = ord(c) - 97if not nodes[index]:return Falseif i == length - 1:if nodes[index].is_word:return Trueelse:return Falsenodes = nodes[index].childrendef startsWith(self, prefix: str) -> bool:"""Returns if there is any word in the trie that starts with the given prefix."""nodes = self.root.childrenlength = len(prefix)for i, c in enumerate(prefix):index = ord(c) - 97if not nodes[index]:return Falseif i == length - 1:return Truenodes = nodes[index].children
方案二(Map)
class Trie:def __init__(self):"""Initialize your data structure here.'bed' -> {'b': {'e': {'d': {'is_word': True}}}}"""self.lookup = {}def insert(self, word: str) -> None:"""Inserts a word into the trie."""node = self.lookupfor c in word:if c not in node:node[c] = {}node = node[c]node['is_word'] = Truedef search(self, word: str) -> bool:"""Returns if the word is in the trie."""node = self.lookupfor c in word:if c not in node:return Falsenode = node[c]# 判断是否是单词if 'is_word' in node:return Truereturn Falsedef startsWith(self, prefix: str) -> bool:"""Returns if there is any word in the trie that starts with the given prefix."""node = self.lookupfor c in prefix:if c not in node:return Falsenode = node[c]return True
原文
https://leetcode-cn.com/explore/learn/card/trie/166/basic-operations/645/
