leetcode面试准备:Implement Trie (Prefix Tree)

1 题目

Implement a trie with insert, search, and startsWith methods.

Note:

You may assume that all inputs are consist of lowercase letters a-z.

2 思路

该题是实现trie树。

Trie,又称单词查找树或键树,是一种树形结构。典型应用是用于统计和排序大量的字符串(但不仅限于字符串),所以经常被搜索引擎系统用于文本词频统计。它的优点是:最大限度地减少无谓的字符串比较,查询效率比哈希表高。

它有3个基本性质:

  • 根节点不包含字符,除根节点外每一个节点都只包含一个字符。
  • 从根节点到某一节点,路径上经过的字符连接起来,为该节点对应的字符串。
  • 每个节点的所有子节点包含的字符都不相同。

此外,每个节点存在一个判断其是否是一个单词结尾的标记,用来表明该trie树中包含该单词。因此我们首先需要定义节点的数据结构。

节点的属性主要包含以下几点:

  • char content:节点字符内容
  • boolean isEnd:节点是否为一个单词结束的标记
  • LinkedList<TrieNode> childNode: 该节点的所有的孩子节点

3 代码

TrieNode

import java.util.LinkedList;

public class TrieNode {
// Initialize your data structure here.
char content; // 节点内容
boolean isEnd;// 是否为一个单词的结尾
LinkedList<TrieNode> childNode;// 该节点所有的孩子节点 // Initialize your data structure here.
public TrieNode() {
this.content = 0;
this.isEnd = false;
this.childNode = new LinkedList<TrieNode>();
} public TrieNode(char content) {
this.content = content;
this.isEnd = false;
this.childNode = new LinkedList<TrieNode>();
} public TrieNode subNode(char c) {
for (TrieNode tn : childNode) {
if (tn.content == c) {
return tn;
}
}
return null;
} @Override
public String toString() {
return ("content:" + content + "\n child:" + childNode.toString());
}
}

Trie

public class Trie {
// 字典树的实现,效率高于HashMap
private TrieNode root; public Trie() {
root = new TrieNode();
} // Inserts a word into the trie.
public void insert(String word) {
if (search(word)) {
return;
}
int len = word.length();
TrieNode cur = root;
for (int i = 0; i < len; i++) {
char c = word.charAt(i);
TrieNode tmp = cur.subNode(c);
if (tmp == null) {
tmp = new TrieNode(c);
cur.childNode.add(tmp);
cur = tmp;
} else {
cur = tmp;
}
}
cur.isEnd = true;
} // Returns if the word is in the trie.
public boolean search(String word) {
int len = word.length();
TrieNode cur = root;
for (int i = 0; i < len; i++) {
char c = word.charAt(i);
TrieNode tmp = cur.subNode(c);
if (tmp == null) {
return false;
} else {
cur = tmp;
}
}
return cur.isEnd;
} // Returns if there is any word in the trie
// that starts with the given prefix.
public boolean startsWith(String prefix) {
int len = prefix.length();
TrieNode cur = root;
for (int i = 0; i < len; i++) {
char c = prefix.charAt(i);
TrieNode tmp = cur.subNode(c);
if (tmp == null) {
return false;
} else {
cur = tmp;
}
}
return true;
} public static void main(String[] args) {
Trie trie = new Trie();
trie.insert("somestring");
trie.insert("key");
boolean res = trie.startsWith("ke");
System.out.println(res);
}
} // Your Trie object will be instantiated and called as such:
// Trie trie = new Trie();
// trie.insert("somestring");
// trie.search("key");

4 总结

很不错的问题,估计面试网易有道,360,百度这样的企业会考到。

leetcode面试准备:Implement Trie (Prefix Tree)的更多相关文章

  1. 【LeetCode】208. Implement Trie (Prefix Tree)

    Implement Trie (Prefix Tree) Implement a trie with insert, search, and startsWith methods. Note:You ...

  2. 【刷题-LeetCode】208. Implement Trie (Prefix Tree)

    Implement Trie (Prefix Tree) Implement a trie with insert, search, and startsWith methods. Example: ...

  3. 【LeetCode】208. Implement Trie (Prefix Tree) 实现 Trie (前缀树)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 公众号:负雪明烛 本文关键词:Leetcode, 力扣,Trie, 前缀树,字典树,20 ...

  4. 【leetcode】208. Implement Trie (Prefix Tree 字典树)

    A trie (pronounced as "try") or prefix tree is a tree data structure used to efficiently s ...

  5. 【LeetCode 208】Implement Trie (Prefix Tree)

    Implement a trie with insert, search, and startsWith methods. Note:You may assume that all inputs ar ...

  6. LeetCode OJ:Implement Trie (Prefix Tree)(实现一个字典树(前缀树))

    Implement a trie with insert, search, and startsWith methods. 实现字典树,前面好像有道题做过类似的东西,代码如下: class TrieN ...

  7. [LeetCode] 208. Implement Trie (Prefix Tree) ☆☆☆

    Implement a trie with insert, search, and startsWith methods. Note:You may assume that all inputs ar ...

  8. 字典树(查找树) leetcode 208. Implement Trie (Prefix Tree) 、211. Add and Search Word - Data structure design

    字典树(查找树) 26个分支作用:检测字符串是否在这个字典里面插入.查找 字典树与哈希表的对比:时间复杂度:以字符来看:O(N).O(N) 以字符串来看:O(1).O(1)空间复杂度:字典树远远小于哈 ...

  9. 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  ...

随机推荐

  1. ajax学习笔记1

    ajax是什么? ajax即“Asynchronous Javascript + XML”(异步JavaScript和XML),是指一种创建交互式网页应用的网页开发技术.能够快速的从服务器获得所需数据 ...

  2. ASP.NET Web Service如何工作(3)

    ASP.NET Web Service如何工作(3) [日期:2003-06-26] 来源:CSDN  作者:sunnyzhao(翻译) [字体:大 中 小] 为了使.asmx句柄有可能反串行化SOA ...

  3. WTL 中的常见问题汇总

    1.CRect,CPoint,CSize的使用 WTL提供了CString,CRect,CPoint和CSize,可能后来版本的ATL也提供了,WTL作者推荐使用ATL的实现,所以:#include ...

  4. 学习C++ Primer 的个人理解(二)

    本身就一定基础的读者我想变量常量这些概念应该已经不是问题了.但是本章还是有几个重点,需要特别留意一下的: 1.初始化和赋值是不同的操作 2.任何非0值都是true 3.使用新标准列表初始化,在有丢失精 ...

  5. 九度OJ 1385 重建二叉树

    题目地址:http://ac.jobdu.com/problem.php?pid=1385 题目描述: 输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树.假设输入的前序遍历和中序遍历的结果中都 ...

  6. hdu 5025 Saving Tang Monk 状态压缩dp+广搜

    作者:jostree 转载请注明出处 http://www.cnblogs.com/jostree/p/4092939.html 题目链接:hdu 5025 Saving Tang Monk 状态压缩 ...

  7. bootstrap和jQuery.Gantt的css冲突问题

    bootstrap是广泛使用的一个前端框架, 而jQuery.Gantt在目前也是一个很好用的用于绘制甘特图的插件.   这次在同时使用它们时,发现甘特图显示异常,如图   不加载bootstrap. ...

  8. winform水晶报表编译错误,未能加载文件或程序集"file:///C:\Program Files\SAP BusinessObjects\Crystal Reports for .NET Framewor "

    未能加载文件或程序集“file:///C:\Program Files\SAP BusinessObjects\Crystal Reports for .NET Framework 4.0\Commo ...

  9. Linux下实现流水灯等功能的LED驱动代码及测试实例

    驱动代码: #include <linux/errno.h> #include <linux/kernel.h> #include <linux/module.h> ...

  10. Boost 1.62.0 编译参数

    # Copyright Vladimir Prus 2002-2006.# Copyright Dave Abrahams 2005-2006.# Copyright Rene Rivera 2005 ...