Leetcode--Java--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
思路
Trie树(字典树)
- 先实现构造函数。
- 判断是否是某个前缀,与查找的实现几乎一样,只要判断能否查找到即可。
- 查找的实现,最后需要判断是否是某个单词的结尾。
代码
class Trie { // 树的结点类 class TreeNode{ boolean isEnd; TreeNode tns[] = new TreeNode[26]; // 字母映射 } private TreeNode root; //根结点 /** Initialize your data structure here. */ public Trie() { root = new TreeNode(); } /** Inserts a word into the trie. */ public void insert(String word) { TreeNode p = root; for (char c: word.toCharArray()) { //求得当前结点的映射 int u = c - a; //如果下一个为空,就创造结点 if (p.tns[u] == null) { p.tns[u] = new TreeNode(); } p = p.tns[u]; } p.isEnd = true; } /** Returns if the word is in the trie. */ public boolean search(String word) { TreeNode p = root; for (char c: word.toCharArray()) { int u = c - a; if (p.tns[u] == null) return false; p = p.tns[u]; } //看是否是某个单词的结尾标记 return p.isEnd; } //和查找部分几乎一样,只要能查找到就肯定是某个的前缀 /** Returns if there is any word in the trie that starts with the given prefix. */ public boolean startsWith(String prefix) { TreeNode p = root; for (char c: prefix.toCharArray()) { int u = c - a; if (p.tns[u] == null) return false; p = p.tns[u]; } //只要查找到了 就肯定是前缀 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); */