实现一个 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;
}
}

最新文章

  1. installshield使用教程
  2. MySQL学习笔记之MySQL安装详解
  3. 数据结构图文解析之:哈夫曼树与哈夫曼编码详解及C++模板实现
  4. Sql Server中不常用的表运算符之APPLY(2)
  5. Java命令行输入求和的简单学习
  6. android广播接收器BroadcastReceiver
  7. sql server 查询多个不关联表且对结果编号
  8. sql 建立数据库,表格,索引,主键
  9. E10后,导致VS2010调试时报错“未能将脚本调试器附加到计算机...&quot;
  10. win7 重启 IIS.
  11. Analyzing the Analyzers 分析分析师 —— 数据科学部门如何建
  12. HDU 4081 MST
  13. POJ 2255 Tree Recovery 二叉树恢复
  14. 使用jstl标签遍历双层的map(map下面的map)
  15. [国嵌攻略][066][ARP协议实现]
  16. Hive metastore整体代码分析及详解
  17. android的Binder通信机制java层浅谈-android学习之旅(88)
  18. Feature Selection Can Reduce Overfitting And RF Show Feature Importance
  19. POJ.2728.Desert King(最优比率生成树 Prim 01分数规划 二分/Dinkelbach迭代)
  20. Transformer-view java实体 转换视图 Lists.transform

热门文章

  1. ceph使用memdisk做journal
  2. 常用linux源列表
  3. flink1.10版本StreamGraph生成过程分析
  4. Nacos一致性算法
  5. 算法题目:北邮python 3-C 排队前进
  6. mysql 5.7添加server_audit 安全审计功能
  7. [代码审计Day2] filter_var函数缺陷代码审计
  8. ABBYY FineReader 15快速转换文档详解
  9. 为什么换了电脑安装MindManager提示密钥失效?
  10. php-fpm和nginx配置