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. 再跟SQL谈一谈--高级篇(一)

    1.SELECT KEYWORD ①TOP ②LIKE ③IN ④BETWEEN...AND ⑤ALIAS 2.SELECT JOIN ①JOIN | INNER JOIN ②LEFT JOIN ③R ...

  2. UIButton关于setFont方法过时的解决方法

    环境:xcode7 语言:Object-c 解决方法:更改UIButton的titleLabel属性的font值 一.新建一个Single View Application项目 二.创建一个UIBut ...

  3. Markdown 生成目录

    <link rel="stylesheet" href="http://yandex.st/highlightjs/6.2/styles/googlecode.mi ...

  4. C# 并行开发总结

    本文内容 均参考自 <C#并行高级编程> TPL 支持 数据并行(有大量数据要处理,必须对每个数据执行同样的操作, 任务并行(有好多可以并发运行的操作),流水线(任务并行和数据并行的结合体 ...

  5. STL的简介

    Standard Template Library,(标准模板库)<来自百度百科的整理> ————可复用性(reusability) STL是基于模板,内联函数的使用使得生成的代码短小高效 ...

  6. 简单模拟struts2核心控制器利用反射原理实现参数传递和物理视图跳转

    在能够运用struts2框架进行简单网站开发后,对struts2的一些较原框架强大的功能希望有更深刻的理解,于是尝试从底层开始摸索,本文就在重新学习struts2后,利用简单代码对核心控制器的主要功能 ...

  7. OS X平台上MySQL环境搭建

    参考资料: http://www.cnblogs.com/macro-cheng/archive/2011/10/25/mysql-001.html http://blog.csdn.net/just ...

  8. Python3 内建模块 hashlib、itertools、HTMLParser、urllib

    Python的hashlib提供了常见的摘要算法,如MD5,SHA1等等. 什么是摘要算法呢?摘要算法又称哈希算法.散列算法.它通过一个函数,把任意长度的数据转换为一个长度固定的数据串(通常用16进制 ...

  9. JS验证用户真实姓名

    发布:thebaby   来源:脚本学堂     [大 中 小] 本文分享下,使用js代码验证用户真实姓名的方法,有需要的朋友不妨参考下,希望对你有一定的帮助. 原文地址:http://www.jbx ...

  10. 一个月时间整理《深入浅出Node.js》

    今天终于把朴灵老师写的<深入浅出Node.js>给学习完了, 这本书不是一本简单的Node入门书籍,它没有停留在Node介绍或者框架.库的使用层面上,而是从不同的视角来揭示Node自己内在 ...