208. 实现 Trie (前缀树)
208. 實現 Trie (前綴樹)
Trie(發音類似 “try”)或者說 前綴樹 是一種樹形數據結構,用于高效地存儲和檢索字符串數據集中的鍵。這一數據結構有相當多的應用情景,例如自動補完和拼寫檢查。
請你實現 Trie 類:
- Trie() 初始化前綴樹對象。
- void insert(String word) 向前綴樹中插入字符串 word 。
- boolean search(String word) 如果字符串 word 在前綴樹中,返回 true(即,在檢索之前已經插入);否則,返回 false 。
- boolean startsWith(String prefix) 如果之前已經插入的字符串 word 的前綴之一為 prefix ,返回 true ;否則,返回 false 。
示例:
輸入
[“Trie”, “insert”, “search”, “search”, “startsWith”, “insert”, “search”]
[[], [“apple”], [“apple”], [“app”], [“app”], [“app”], [“app”]]
輸出
[null, null, true, false, true, null, true]
解釋
Trie trie = new Trie();
trie.insert(“apple”);
trie.search(“apple”); // 返回 True
trie.search(“app”); // 返回 False
trie.startsWith(“app”); // 返回 True
trie.insert(“app”);
trie.search(“app”); // 返回 True
提示:
1 <= word.length, prefix.length <= 2000
word 和 prefix 僅由小寫英文字母組成
解題思路
字典樹的核心數據結構就是一顆多叉樹,我們根據第i層的第j個節點是否為空,判斷是否存在字符串在第i個位置的值為(char)(j+‘a’),通過這樣一顆樹,我們可以快速判斷我們的輸入字符串,是否存在于已有字符串里面
代碼
class Trie {Node root =new Node();/** Initialize your data structure here. */public Trie() {}/** Inserts a word into the trie. */public void insert(String word) {Node cur=root;for(int i=0;i<word.length();i++){if(cur.nodes[word.charAt(i)-'a']==null) cur.nodes[word.charAt(i)-'a']=new Node();cur=cur.nodes[word.charAt(i)-'a'];}cur.isEnd=true;}/** Returns if the word is in the trie. */public boolean search(String word) {Node cur=root;for(int i=0;i<word.length();i++){if(cur.nodes[word.charAt(i)-'a']!=null)cur=cur.nodes[word.charAt(i)-'a'];else return false;}return cur.isEnd;}/** Returns if there is any word in the trie that starts with the given prefix. */public boolean startsWith(String word) {Node cur=root;for(int i=0;i<word.length();i++){if(cur.nodes[word.charAt(i)-'a']!=null)cur=cur.nodes[word.charAt(i)-'a'];else return false;}return true;} }class Node{Node[] nodes;boolean isEnd=false;public Node(){nodes=new Node[26];}}/*** Your Trie object will be instantiated and called as such:* Trie obj = new Trie();* obj.insert(word);* boolean param_2 = obj.search(word);* boolean param_3 = obj.startsWith(prefix);*/總結
以上是生活随笔為你收集整理的208. 实现 Trie (前缀树)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 梦到朋友出车祸是什么意思
- 下一篇: 面试题 17.14. 最小K个数