208. Implement Trie (Prefix Tree)
Posted 白天黑夜每日c
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了208. Implement Trie (Prefix Tree)相关的知识,希望对你有一定的参考价值。
Implement a trie with insert
, search
, and startsWith
methods.
Note:
You may assume that all inputs are consist of lowercase letters a-z
.
这棵Trie树里存的都是英文小写字母,因此每个Node有26个孩子,代表它的下一个字符a-z。同时,每个节点中,用count记录到这个节点是否是一个endpoint
** 这里没有对Trie树做删除的操作。在查找prefix时,我是判断如果对prefix里的字符一个个遍历,如果节点都不为空,表示存在以Prefix为前缀的字符串。*如果加上删除操作,要确保把Trie里的整条路径删除。
思考:Trie Tree的优缺点有什么?
public class Trie { Trie[] children; int count = 0; /** Initialize your data structure here. */ public Trie() { children = new Trie[26]; } /** Inserts a word into the trie. */ public void insert(String word) { if (word.equals("")) { count++; } Trie cur = this; int i = 0; while (i < word.length()) { if (cur.children[word.charAt(i) - ‘a‘] == null) { cur.children[word.charAt(i) - ‘a‘] = new Trie(); } cur = cur.children[word.charAt(i) - ‘a‘]; i++; } cur.count++; } /** Returns if the word is in the trie. */ public boolean search(String word) { Trie cur = this; int i = 0; while (cur != null && i < word.length()) { cur = cur.children[word.charAt(i) - ‘a‘]; i++; } if (cur == null || cur.count == 0) { return false; } return true; } /** Returns if there is any word in the trie that starts with the given prefix. */ public boolean startsWith(String prefix) { Trie cur = this; int i = 0; while (cur != null && i < prefix.length()) { cur = cur.children[prefix.charAt(i) - ‘a‘]; i++; } if (cur == null) { return false; } return true; } } /** * 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. Implement Trie (Prefix Tree)的主要内容,如果未能解决你的问题,请参考以下文章
208. Implement Trie (Prefix Tree)
208. Implement Trie (Prefix Tree)
208. Implement Trie (Prefix Tree)
208. Implement Trie (Prefix Tree)