Implement a Trie Data Structure, and search() & insert() function:

we need to implement both Class Trie and Class TrieNode

Class Trie:

 import java.util.ArrayList;
import java.util.List; public class Trie
{
private TrieNode root; /**
* Constructor
*/
public Trie()
{
root = new TrieNode();
} /**
* Adds a word to the Trie
* @param word
*/
public void addWord(String word)
{
root.addWord(word.toLowerCase());
} /**
* Get the words in the Trie with the given
* prefix
* @param prefix
* @return a List containing String objects containing the words in
* the Trie with the given prefix.
*/
public List getWords(String prefix)
{
//Find the node which represents the last letter of the prefix
TrieNode lastNode = root;
for (int i=0; i<prefix.length(); i++)
{
lastNode = lastNode.getNode(prefix.charAt(i)); //If no node matches, then no words exist, return empty list
if (lastNode == null) return new ArrayList();
} //Return the words which eminate from the last node
return lastNode.getWords();
}
}

Class TrieNode:

 import java.util.ArrayList;
import java.util.List; public class TrieNode
{
private TrieNode parent;
private TrieNode[] children;
private boolean isLeaf; //Quick way to check if any children exist
private boolean isWord; //Does this node represent the last character of a word
private char character; //The character this node represents /**
* Constructor for top level root node.
*/
public TrieNode()
{
children = new TrieNode[26];
isLeaf = true;
isWord = false;
} /**
* Constructor for child node.
*/
public TrieNode(char character)
{
this();
this.character = character;
} /**
* Adds a word to this node. This method is called recursively and
* adds child nodes for each successive letter in the word, therefore
* recursive calls will be made with partial words.
* @param word the word to add
*/
protected void addWord(String word)
{
isLeaf = false;
int charPos = word.charAt(0) - 'a'; if (children[charPos] == null)
{
children[charPos] = new TrieNode(word.charAt(0));
children[charPos].parent = this;
} if (word.length() > 1)
{
children[charPos].addWord(word.substring(1));
}
else
{
children[charPos].isWord = true;
}
} /**
* Returns the child TrieNode representing the given char,
* or null if no node exists.
* @param c
* @return
*/
protected TrieNode getNode(char c)
{
return children[c - 'a'];
} /**
* Returns a List of String objects which are lower in the
* hierarchy that this node.
* @return
*/
protected List getWords()
{
//Create a list to return
List list = new ArrayList(); //If this node represents a word, add it
if (isWord)
{
list.add(toString());
} //If any children
if (!isLeaf)
{
//Add any words belonging to any children
for (int i=0; i<children.length; i++)
{
if (children[i] != null)
{
list.addAll(children.getWords()); } } } return list; } /** * Gets the String that this node represents. * For example, if this node represents the character t, whose parent * represents the charater a, whose parent represents the character * c, then the String would be "cat". * @return */ public String toString() { if (parent == null) { return ""; } else { return parent.toString() + new String(new char[] {character}); } } }

Summary: Trie Data Structure的更多相关文章

  1. [Algorithm] Trie data structure

    For example we have an array of words: [car, done, try, cat, trie, do] What is the best data structu ...

  2. (Data structure)Implement Trie && Add and Search Word

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

  3. leetcode 211. Add and Search Word - Data structure design Trie树

    题目链接 写一个数据结构, 支持两种操作. 加入一个字符串, 查找一个字符串是否存在.查找的时候, '.'可以代表任意一个字符. 显然是Trie树, 添加就是正常的添加, 查找的时候只要dfs查找就可 ...

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

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

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

  6. [leetcode trie]211. Add and Search Word - Data structure design

    Design a data structure that supports the following two operations: void addWord(word) bool search(w ...

  7. [LeetCode] Add and Search Word - Data structure design 添加和查找单词-数据结构设计

    Design a data structure that supports the following two operations: void addWord(word) bool search(w ...

  8. Finger Trees: A Simple General-purpose Data Structure

    http://staff.city.ac.uk/~ross/papers/FingerTree.html Summary We present 2-3 finger trees, a function ...

  9. Java for LeetCode 211 Add and Search Word - Data structure design

    Design a data structure that supports the following two operations: void addWord(word)bool search(wo ...

随机推荐

  1. Python中什么是set、更新、遍历set和set的特点

    dict的作用是建立一组 key 和一组 value 的映射关系,dict的key是不能重复的. 有的时候,我们只想要 dict 的 key,不关心 key 对应的 value,目的就是保证这个集合的 ...

  2. go 安装

    安装golang centos7 直接安装golang yum install golang centos6需添加软件源,然后再安装 rpm -ivh http://ftp.riken.jp/Linu ...

  3. Qt中sleep()的实现(耳目一新的两种方法)

    在Qt中并没有Sleep函数可以调用,在程序编写时往往需要休眠几秒,这里举出两个方法,不知道是否啥不良隐患没~~ 方法一: class SleeperThread : public QThread{p ...

  4. 【Android测试】【第一节】ADB——初识和用法

    ◆版权声明:本文出自胖喵~的博客,转载必须注明出处.  转载请注明出处:http://www.cnblogs.com/by-dream/p/4630046.html 写在前面的话 感觉自己进入Andr ...

  5. 安装PHPStudy2014,打开端口出现80端口 PID4 进程:System-windows服务器应用

    原文:安装PHPStudy2014,打开端口出现80端口 PID4 进程:System-windows服务器应用-黑吧安全网 安装PHPStudy2014,打开端口出现80端口 PID4 进程:Sys ...

  6. Nmap 網路診斷工具基本使用技巧與教學

    Nmap 是一個開放原始碼的網路掃描與探測工具,可以讓網路管理者掃描整個子網域或主機的連接埠等,功能非常強大. Nmap(Network Mapper)是一個開放原始碼的網路檢測工具,它的功能非常強大 ...

  7. [LeetCode]题解(python):081 - Search in Rotated Sorted Array II

    题目来源 https://leetcode.com/problems/search-in-rotated-sorted-array-ii/ Follow up for "Search in ...

  8. [iOS]如何把App打包成ipa文件,然后App上架流程[利用Application Loader]

    摘自:http://www.cnblogs.com/wangqi1221/p/5240281.html 在上一篇博客已经讲过上传项目了,但是有的时候,需要我们进行打包成ipa包到别的手机上跑(但是前提 ...

  9. 深度学习笔记(三 )Constitutional Neural Networks

    一. 预备知识 包括 Linear Regression, Logistic Regression和 Multi-Layer Neural Network.参考 http://ufldl.stanfo ...

  10. Speed-BI数据分析案例:2016年7月汽车销量排行榜

    据中国汽车工业协会统计分析,2016年7月,汽车产销比上月均呈下降,同比呈较快增长.1-7月,汽车产销保持稳定增长,增幅比上半年继续提升. 7月,汽车生产195.96万辆,环比下降4.38%,同比增长 ...