数据结构—— Trie (前缀树)
2024-09-07 10:37:53
实现一个 Trie (前缀树),包含 插入, 查询, 和 查询前缀这三个操作。
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
思路:构造一个多叉树数据结构,每个父节点最多有26个子节点,分别表示26个字母,同时每个节点还存在一个结尾标志位,表示该节点是否位一个单词的末尾节点。树的操作是重点,首先在全局变量中,我们得到树的根节点,每次操作都从根节点出发。
插入操作就是遍历树,如果不存在相应的节点则实例化新节点,直到遍历到尾节点,并将尾节点的标志置为。
查询和查询前缀的方法类似,对树进行遍历,不存在节点直接返回false,最后返回判断尾节点的标志位。
class Node {
public Node[] val;
public boolean isEnd = false;
public Node() {
val = new Node[26];
}
}
class Trie {
Node root;
/** Initialize your data structure here. */
public Trie() {
root = new Node();
}
/** Inserts a word into the trie. */
public void insert(String word) {
Node cur = root;
for(int i = 0; i < word.length(); i ++) {
if(cur.val[word.charAt(i) - 'a'] == null) {
cur.val[word.charAt(i) - 'a'] = new Node();
}
cur = cur.val[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.val[word.charAt(i) - 'a'] == null) return false;
cur = cur.val[word.charAt(i) - 'a'];
}
return cur.isEnd;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
public boolean startsWith(String prefix) {
Node cur = root;
for(int i = 0; i < prefix.length(); i++) {
if(cur.val[prefix.charAt(i) - 'a'] == null) return false;
cur = cur.val[prefix.charAt(i) - 'a'];
}
return true;
}
}
最新文章
- installshield使用教程
- MySQL学习笔记之MySQL安装详解
- 数据结构图文解析之:哈夫曼树与哈夫曼编码详解及C++模板实现
- Sql Server中不常用的表运算符之APPLY(2)
- Java命令行输入求和的简单学习
- android广播接收器BroadcastReceiver
- sql server 查询多个不关联表且对结果编号
- sql 建立数据库,表格,索引,主键
- E10后,导致VS2010调试时报错“未能将脚本调试器附加到计算机...";
- win7 重启 IIS.
- Analyzing the Analyzers 分析分析师 —— 数据科学部门如何建
- HDU 4081 MST
- POJ 2255 Tree Recovery 二叉树恢复
- 使用jstl标签遍历双层的map(map下面的map)
- [国嵌攻略][066][ARP协议实现]
- Hive metastore整体代码分析及详解
- android的Binder通信机制java层浅谈-android学习之旅(88)
- Feature Selection Can Reduce Overfitting And RF Show Feature Importance
- POJ.2728.Desert King(最优比率生成树 Prim 01分数规划 二分/Dinkelbach迭代)
- Transformer-view java实体 转换视图 Lists.transform