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. cluster analysis in data mining

    https://en.wikipedia.org/wiki/K-means_clustering k-means clustering is a method of vector quantizati ...

  2. php thread

    1-include('w_fun.php');页面已经在执行,则修改include中的函数,倒置旧页面不受影响:新页面生效:2-time  轮流 echo ' <script> windo ...

  3. double-clicking

    <!doctype html> <button id="id0" onclick="w('id0','str0')">target0&l ...

  4. java Semaphore

    //Listing 6-4. Using a Counting Semaphore to Control Access to a Pool of Items import java.util.conc ...

  5. 使用dotTrace6.0进行内存分析

    dotTrace6.0提供了内存分析功能,统计抓取的时间段内各个堆栈执行过程中使用的内存大小,按照堆栈执行情况树状排序:和它之前提供的时间统计类似,粗截了几个页面,希望对大家有所帮助. 下载安装Jet ...

  6. zepto源码--整体框架--学习笔记

    为了深入学习javascript,根据别人推荐的方法之一:研究源码. 相对而言,之前的项目中仅仅使用过zepto和jquery,当前阶段,看到好几千行的jquery源码,心生敬畏,望而却步,所以选择相 ...

  7. HttpPost发送Json

    1.public static JSONObject post(String url,JSONObject json){ 2. HttpClient client = new DefaultHttpC ...

  8. [LeetCode] Jump Game II(贪婪算法)

    Given an array of non-negative integers, you are initially positioned at the first index of the arra ...

  9. Linux-modules software

    简介 这里指的modules不是linux内核相关的module,只是用于软件多版本控制的一个开源软件包,比如说系统同时有neo4j的不同版本,使用modules软件就可以使得在需要的时候选择相应的软 ...

  10. UITabBar 设置字体的颜色(选中状态/正常状态)setTitleTextAttributes

    UITabbar有个setTintColor这个方法,可以理解为,高亮的时候,或者点击后的颜色设置. UITabBarItem有个setTitleTextAttributes的方法,是用来设置字体的颜 ...