package com.heu.wsq.leetcode.ashe_ji_ti;
/**
* 208. 实现 Trie (前缀树)
* @author wsq
* @date 2021/4/14
* 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
*
* 链接:https://leetcode-cn.com/problems/implement-trie-prefix-tree
*/
public class Trie {
/**
* 该节点对应的孩子数,每个节点都可能由对应的26个英文字母对应
*/
private Trie[] children;
/**
* 标志该点是否是最终节点
*/
private boolean isEnd;
/** Initialize your data structure here. */
public Trie() {
this.children = new Trie[26];
this.isEnd = false;
}
/**
* 前缀树一般分为两个操作:插入和查询
* 字符串插入的思想可分为两步:
* 1.从root匹配子节点,如果没有对应的子节点,就创建新节点,并与root节点相连,转到步骤3
* 2.如果有对应的子节点,直接转到步骤3
* 3.继续沿着对应的子节点进行插入
* @param word
*/
public void insert(String word) {
// 插入有两种情况
// 1.已存在对应节点
// 2.不存在对应节点
char[] arr = word.toCharArray();
Trie trie = this;
for(char c: arr){
int pos = c - 'a';
if (trie.children[pos] == null){
trie.children[pos] = new Trie();
}
trie = trie.children[pos];
}
trie.isEnd = true;
}
/**
* 查询操作,就是查询一个字符串S是不是在集合中。
* 如果字符串S在该树中,则能完成字符串的全部匹配,
* 且最后一个节点的isEnd属性是true,表示插入了对应字符串
* @param word
* @return
*/
public boolean search(String word) {
// 搜索字符串是否存在
Trie node = searchPrefix(word);
return node != null && node.isEnd;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
public boolean startsWith(String prefix) {
Trie node = searchPrefix(prefix);
return node != null;
}
private Trie searchPrefix(String word){
int n = word.length();
Trie node = this;
for(int i = 0; i < n; i++){
char c = word.charAt(i);
int pos = c - 'a';
if(node.children[pos] == null){
return null;
}
node = node.children[pos];
}
return node;
}
}
208. 实现 Trie (前缀树)
最新推荐文章于 2024-08-27 10:11:24 发布
本文详细介绍了如何实现Trie数据结构,包括插入、搜索和判断前缀的功能。通过示例展示了Trie在字符串存储和检索中的效率,并提供了具体的Java代码实现。
1505

被折叠的 条评论
为什么被折叠?



