Implement Trie (Prefix Tree) 解答
Question
Implement a trie with insert
, search
, and startsWith
methods.
Note:
You may assume that all inputs are consist of lowercase letters a-z
.
Solution
A trie node should contains the character, its children and the flag that marks if it is a leaf node.
Trie is an efficient information retrieval data structure. Using trie, search complexities can be brought to optimal limit (key length).
Every node of trie consists of multiple branches. Each branch represents a possible character of keys. We need to mark the last node of every key as leaf node.
We design TrieNode to store 1. value 2. isLeaf 3. a map of children (map is used for quick selection)
In this way, we can implement Trie start from root. Add new child to original parent is implemented by put action in map.
Note here, search and startsWith differs.
null
|
a
|
b
for "a", search will return false, while startsWith will return true.
/**
* Your Trie object will be instantiated and called as such:
* Trie trie = new Trie();
* trie.insert("lintcode");
* trie.search("lint"); will return false
* trie.startsWith("lint"); will return true
*/
class TrieNode {
char val;
boolean isLast;
Map<Character, TrieNode> children;
// Initialize your data structure here.
public TrieNode(char val) {
children = new HashMap<Character, TrieNode>();
this.val = val;
this.isLast = false;
}
} public class Trie {
private TrieNode root; public Trie() {
root = new TrieNode(' ');
} // Inserts a word into the trie.
public void insert(String word) {
if (word == null || word.length() == 0) {
return;
}
TrieNode p = this.root;
char[] arr = word.toCharArray();
for (char cur : arr) {
if (!p.children.containsKey(cur)) {
p.children.put(cur, new TrieNode(cur));
}
p = p.children.get(cur);
}
p.isLast = true;
} // Returns if the word is in the trie.
public boolean search(String word) {
if (word == null || word.length() == 0) {
return false;
}
char[] arr = word.toCharArray();
TrieNode p = this.root;
for (char cur : arr) {
Map<Character, TrieNode> children = p.children;
if (!children.containsKey(cur)) {
return false;
}
p = children.get(cur);
}
return p.isLast;
} // Returns if there is any word in the trie
// that starts with the given prefix.
public boolean startsWith(String prefix) {
if (prefix == null || prefix.length() == 0) {
return false;
}
char[] arr = prefix.toCharArray();
TrieNode p = this.root;
for (char cur : arr) {
Map<Character, TrieNode> children = p.children;
if (!children.containsKey(cur)) {
return false;
}
p = children.get(cur);
}
return true;
}
}
Implement Trie (Prefix Tree) 解答的更多相关文章
- leetcode面试准备:Implement Trie (Prefix Tree)
leetcode面试准备:Implement Trie (Prefix Tree) 1 题目 Implement a trie withinsert, search, and startsWith m ...
- 【LeetCode】208. Implement Trie (Prefix Tree)
Implement Trie (Prefix Tree) Implement a trie with insert, search, and startsWith methods. Note:You ...
- [LeetCode] 208. Implement Trie (Prefix Tree) ☆☆☆
Implement a trie with insert, search, and startsWith methods. Note:You may assume that all inputs ar ...
- 字典树(查找树) leetcode 208. Implement Trie (Prefix Tree) 、211. Add and Search Word - Data structure design
字典树(查找树) 26个分支作用:检测字符串是否在这个字典里面插入.查找 字典树与哈希表的对比:时间复杂度:以字符来看:O(N).O(N) 以字符串来看:O(1).O(1)空间复杂度:字典树远远小于哈 ...
- LeetCode208 Implement Trie (Prefix Tree). LeetCode211 Add and Search Word - Data structure design
字典树(Trie树相关) 208. Implement Trie (Prefix Tree) Implement a trie with insert, search, and startsWith ...
- 【刷题-LeetCode】208. Implement Trie (Prefix Tree)
Implement Trie (Prefix Tree) Implement a trie with insert, search, and startsWith methods. Example: ...
- 【LeetCode】208. Implement Trie (Prefix Tree) 实现 Trie (前缀树)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 公众号:负雪明烛 本文关键词:Leetcode, 力扣,Trie, 前缀树,字典树,20 ...
- Leetcode: Implement Trie (Prefix Tree) && Summary: Trie
Implement a trie with insert, search, and startsWith methods. Note: You may assume that all inputs a ...
- 【leetcode】208. Implement Trie (Prefix Tree 字典树)
A trie (pronounced as "try") or prefix tree is a tree data structure used to efficiently s ...
随机推荐
- Android应用开发学习之AlertDialog对话框
作者:刘昊昱 博客:http://blog.csdn.net/liuhaoyutz 本文中我们通过一个例子来看AlertDialog对话框的实现,其运行效果如下: 主布局文件main.xml内容如下: ...
- Ubuntu 配置Tomcat环境
1.下载Tomcat http://tomcat.apache.org/,下载Tomcat 8(由于目前最新eclipse不支持tomcat 9) 将下载的apache-tomcat-8.0.35.t ...
- mysql补充(1)校对集utf8_unicode_ci与utf8_general_ci
创建数据库并设置编码utf-8 多语言(补充1 2) create database mydb default character set utf8 collate utf8_general_ci; ...
- pyqt 动态显示时间方法例子学习
# -*- coding: utf-8 -*- # python:2.x __author__ = 'Administrator' import sys,datetime from PyQt4.QtC ...
- hdu3397 Sequence operation
感觉自己好像搞定了一个不得了得题呢.. 对于这种区间性质合并的线段树,对于每个节点保存一下当前区间内1的个数,左右边界相邻的1个的个数与0的个数,还有当前区间最大连续的1和0的个数. 合并的时候的细节 ...
- java与.net比较学习系列(4) 运算符和表达式
上一篇总结了java的数据类型,得到了冰麟轻武等兄弟的支持,他们提出并补充了非常好的建议,在这里向他们表示感谢.在后面的文章中,我会尽力写得更准确和更完善的,加油! 另外,因为C#是在java之后,也 ...
- 一步步学算法(算法分析)---6(Floyd算法)
Floyd算法 Floyd算法又称为弗洛伊德算法,插点法,是一种用于寻找给定的加权图中顶点间最短路径的算法.该算法名称以创始人之一.1978年图灵奖获得者.斯坦福大学计算机科学系教授罗伯特·弗洛伊德命 ...
- 关于MemoryBarrier
备注:OSG OpenThread::Atomic.cpp中MemoryBarrier(); Atomic::operator unsigned() const { #if defined(_OPE ...
- Android内存泄漏监测(MAT)及解决办法
http://ttlnews.blogspot.com/2010/01/attacking-memory-problems-on-android.html 这篇文章是2010年1月份写的,其中有些已经 ...
- stagefright omx小结
由于stagefright和openmax运行在两个不同的进程上,所以他们之间的通讯要经过Binder进行处理,本小结不考虑音频这一块,假设视频为MP4封装的AVC编码文件. 先简单的看一下stage ...