Today, I saw Trie's principles. I thought of a question I had not answered in my previous interview. I 'd like to try it out by writing some code.
A typical Trie application is used for statistics and sorting, and to query a large number of strings, but not limited to strings). Therefore, it is often used by the search engine system for text word frequency statistics. If the maximum length of a keyword is 5, you can use the trie tree to retrieve the specified keyword from 26 ^ 5 = 11881376 possible keywords using 5 comparisons. Log2n comparison is required at least for the binary search tree.
If you want to calculate the term frequency, you need to modify the Node class. For a given word table, this data structure can be used to search for words in the text in a poor word table.
package algorithm;import java.util.ArrayList;import java.util.HashMap;import java.util.List;public class Trie { private Node root=new Node(); public static void main(String[] args) { Trie trie = new Trie(); List<String> keyWords=new ArrayList<String>(); keyWords.add("ca123"); keyWords.add("mu456"); keyWords.add("zh789"); trie.buildTrie(keyWords); trie.search("ca123"); trie.search("ca124"); trie.search("mu445"); trie.search("zh789"); } public void buildTrie(List<String> keyWords){ for(String key:keyWords){ Node parent=root; for (int i = 0; i < key.length(); i++) { char nodeKey=key.charAt(i); Node node = parent.getChildNodes().get(nodeKey); if (node!=null) { parent=node; } else { Node childNode = new Node(); parent.getChildNodes().put(nodeKey, childNode); parent=childNode; } } parent.setValue(key); } } public void search(String key){ Node parent=root; for (int i = 0; i < key.length(); i++) { Node node = parent.getChildNodes().get(key.charAt(i)); if (node == null) { System.out.println("The word "+key+" is not in dictionary"); return; } parent=node; } System.out.println("The word "+parent.getValue()+" is in the dictionary"); } }class Node { private String value; private HashMap<Character, Node> childNodes; public String getValue() { return value; } public void setValue(String value) { this.value = value; } public HashMap<Character, Node> getChildNodes() { if (childNodes==null) { childNodes=new HashMap<Character, Node>(); } return childNodes; } public void setChildNodes(HashMap<Character, Node> childNodes) { this.childNodes = childNodes; } }
This article from the "Ying: Good memory as bad pen" blog, please be sure to keep this source http://yingtju.blog.51cto.com/3760152/1299564