150強訪談中等

實作 Trie 前綴樹

「實作 Trie 前綴樹」問題的詳細指南和 Python 實作。

問題陳述

中等

trie(發音為“try”)或前綴樹是一種樹資料結構,用於有效地儲存和檢索字串資料集中的鍵。這種資料結構有多種應用,例如自動完成和拼字檢查。

實作 Trie 類:

- Trie() 初始化 trie 物件。

- insert(word: str) 將字串 word 插入 trie 中。

- search(word: str) -> bool 如果字串 word 在 trie 中(即之前插入過),則傳回 True,否則傳回 False。

-startsWith(prefix:str)->bool 如果先前插入的字串單字具有前綴 prefix,則傳回 True,否則傳回 False。

輸入是操作和參數的清單。實作一個函數 trie(operations: list, arguments: list) -> list 傳回結果列表(建構子/插入為 None,搜尋/startsWith 為 bool)。

約束條件
  • 1 <= len(word), len(prefix) <= 2000
  • word and prefix consist of lowercase English letters
  • At most 3 * 10^4 calls will be made in total to insert, search, and startsWith

範例

Example 1
Input
operations = ["Trie", "insert", "search", "search", "startsWith", "insert", "search"], arguments = [[], ["apple"], ["apple"], ["app"], ["app"], ["app"], ["app"]]
Output
[None, None, True, False, True, None, True]
Explanation

Trie initialized. insert("apple"). search("apple") returns True. search("app") returns False. startsWith("app") returns True. insert("app"). search("app") returns True.

Need a Hint?
考慮使用 Trie 特定的資料結構,例如集合或堆疊。
Edge Cases to Watch
  • 空輸入結構
  • 單元素輸入
  • 大數值範圍

準備好解決了嗎?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

在編輯器中開啟
Found this breakdown helpful?

PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!

Buy me a coffee

推薦的 Python 資源

透過相關的互動式教學、備忘單和程式碼比較來擴展您的知識。