Hihocoder Trie Tree Java implementation

Source: Internet
Author: User

Too late to know this platform, or received a written notice of MS to know, platform is really good.
To the point, the problem description:

1014:trie Tree

Time limit: 10000ms
Single point time limit: 1000ms
Memory Limit: 256MB

Describe

Small hi and small ho is a pair of good friends, born in the information society, they have a great interest in programming, they agreed to help each other, in the programming of learning along the road together.

This day, they met a dictionary, so little hi to small ho raised the classic question: "Little ho, can you for each of the strings I gave, in this dictionary to find all the words starting with this string?" ”

The battle-hardened Little Ho replied: "How can not it!" You give me a string, I go through all the words in the dictionary, check that you give me the string is not the prefix of this word is it? ”

Little hi smiled: "You ah, still too young!" ~ Suppose there are 100,000 words in this dictionary, I ask you 10,000 times, which month do you have to count? ”

Small Ho bowed down a count, look at that pile of 0, immediately feel oneself this life will spend on above ...

Small hi look at small ho's embarrassing kind, also continue to smile: "Let me improve your knowledge level bar ~ Do you know the tree such a data structure?" ”

Small Ho thought, said: "Know ~ it is a basic data structure, as here said!" ”

Small hi satisfied nodded, said: "Then you know how I use a tree to represent the whole dictionary?" ”

Little Ho shook his head and said he was not clear.

Small hi so on the paper for a while, handed to small ho, the way: "You see this tree and this dictionary have what relationship?" ”

Little Ho stared at the paper and thought for a minute: "I know!" For the path from the root node of the tree to each black node, if the letters on the path are connected, they all correspond to one word in the dictionary! ”

Little Hi said: "Then do you know how to build such a tree from a dictionary?" ”

"Not Made!" ”

"Think you do not know, I come to tell you ~" Little Hi put on a teacher's appearance, said: "You think so, if I already have a dictionary and a corresponding tree, I want to add a new word apart, what should I do? ”

"Let me think ..." Little Ho began to wonder: "First I have to see where I can go, right?" For example, I walk from the number 1th node "a" This side can go to the number 2nd node, and then from the 2nd node Walk "p" this side can go to the 3rd node, and then ... There's no way to go! At this point I need to add a line from node 3rd and marked "P" to go down ... This is the end! Then I'll mark the last node that I arrived at as black. ”

Small hi said: "Really clever ~ then you might as well if it is a dictionary with 10W words, the length of each word is not more than 10, how big is this tree?" ”

Little Ho then took out his pen and said: "Assuming I have made the first three words into a tree, then I want to add a new word, the worst case is that the word and the previous three words do not have a common prefix, then the length of the new word if it is 5, I will add at least 5 nodes to the tree in order to continue to represent this dictionary! ”

"And if every time is the worst case, the tree will have a maximum of 100W knots!" Not to mention the worst-case scenario is unlikely to happen a second time! After all, the alphabet is only 26 letters! "said Little Ho, continuing.

"Hmm ~ so we can use (the number of words * word length) a node to represent a dictionary?" Little Hi asked.

"Yes!" "Little ho Way:" But what's the use of such a tree? ”

"Do not underestimate it, it is the legendary trie tree Oh ~ As to what he has to use, a while you will know!" "Little hi smiled and answered."

"You see, we have now got such a tree, then you see, if I give you a string AP, how do you find all the words that start with the AP?" "Little hi again began to test Xiao Ho."

"Hmm ... Iterate through all the words? Little Ho still does not forget the algorithm that he first proposed.

Stupid This tree is built in white! "Little Hi, after the little Ho," continued the way: "Watch! ”

Small hi in the tree with green marked a node, handed to small ho.

"This knot ... is to go from the root node first "a" and then go "p" to reach the node it! Oh, I know, all the markers in the subtree with this node root are words prefixed with "AP"! And all words prefixed with "AP" are in a subtree rooted in this node ~ "Little ho surprises."

"Yes, and you have an idea of how to solve my problem?" "Little Hi Chase asked."

"Hmm ... That is, every time I get your string, I find the corresponding node in the tree, and then count how many of the nodes are there? "Little Ho is not very sure to answer:" But this ... It seems that in the worst case, when you give a string a short time, I still have to scan a large part of this tree? This means that while the average time complexity is reduced, the worst-case time complexity is still high! ”

Small hi smiled: "I did not expect you to see out of it ~ I thought it would teach you again!" ~ Well, do you have any good solutions? ”

"Not yet!" Little hi You don't suspense, tell me now! The tortured little Ho began to beg for mercy.

"All right!" I will help you this time ~ "

"Little Ho Have you ever thought of such a question?" It may be said that the number of nodes in the subtree of the root of T is l[t], since I want to count a l[t1], and this node is uncertain, I have no way to all the nodes of the l[t] to find out? "Little hi tidied up the thoughts, asked."

"There seems to be some," the teacher said before, "What is recursion?" Little Ho replied.

"Recursion is too complicated!" We can say later, you think, when you build the trie tree, when you go through a node, what does it say? "Little Hi left the head," continued the ask.

"I think, after a knot ... Tag node ... It shows that the subtree with this node as the root will have more than one marker node? ”

Yes Do you have any way to record this change? ”

"I think I'm going to start with all the l[t]=0, and then every time I add a new word, all the nodes that pass through the l[t] are all +1, so I can count all the l[t at the same time when I'm finished building this trie tree, right? "Little Ho Happy Road."

"Then now!" Go to the code to achieve it! "said Little hi.
Input

The first behavior of the input is a positive integer n, which indicates the size of the dictionary, followed by n lines, one word per line (not guaranteed to be an English word, or possibly a Martian word), a word consisting of no more than 10 lowercase English letters, possibly with the same word, which should be treated as a different word. The next behavior is a positive integer m, which indicates the number of times the small hi inquired, followed by the M-line, each line a string consisting of a lowercase English letter of not more than 10, which represents a query for small hi.

In 20% of the data is N, m<=10, the dictionary size <=2.

In 60% of the data is N, m<=1000, the dictionary size <=5.

In 100% of the data is N, m<=100000, the dictionary size <=26.

The subject by the amount of data to be ranked Oh ~
Output

For each query of little hi, output an integer ans, which represents the number of words prefixed by the string in the dictionary given by small hi.
Sample input

5babaabbabbbaaaaabbaaaaaabaababaababb5babbbaabaaababbbbbabbaab

Sample output

10300

Data:

privateclass TrieNode{        privateint num;        private Map<Character,TrieNode> sons;        private boolean isEnd;        TrieNode(){            num=0;            new HashMap<Character,TrieNode>();            false;        }    }

Realization of the idea: by HashMap<Character,TrieNode>() Implementing, the same layer of the node allocation, for example: {"abc", "Udo", "Ikn"} These three words, belong to the same layer is the first letter of each word, "a" in "ABC", "Udo" in "U", "ikn" in "I".
The hashmap operation of the above three words can be similar to the following:

Here is the implementation code:
Trietree Class Members:

private TrieNode root;

Node structure:

privateclass TrieNode{        privateint num;//记录频数        private Map<Character,TrieNode> sons;//节点结构        private boolean isEnd;//结束标志        //初始化节点        TrieNode(){            num=0;            new HashMap<Character,TrieNode>();            false;        }    }

constructor function:

 TrieTree(){        root = new TrieNode();    }

Node insertion:

     Public void Insert(String Word) {//Character not normal        if(Word.length () <=0|| word==NULL)return; Trienode node = root; for(inti =0; I<word.length (); i++) {//map does not contain this character, a new node is assigned           if(! (Node.sons.containsKey (Word.charat (i)))) {Node.sons.put (Word.charat (i),NewTrienode ()); }//contains the word Fu Zeping number +1node = node.sons.Get(Word.charat (i));        node.num++; }//Mark EndNode.isend =true; }

Prefix Occurrence frequency:

  Public int Countprefix(String prefix) {//non-normal prefix        if(Prefix.length () <=0|| Prefix.trim () = =NULL)return-1;//Normal prefixTrienode node = root; for(inti =0; I < Prefix.length (); i++) {if(Node.sons.containsKey (Prefix.charat (i))) {node = node.sons.Get(Prefix.charat (i)); }Else{return 0; }        }//return prefix frequency         returnNode.num; }

Main function:

Testtrie tree =NewTesttrie ();//Console inputScanner input =NewScanner (System.inch);//Array size        intnum = Input.nextint (); string[] STRs =NewString[num];//Initialize array         for(inti =0; i < num; i++) {Strs[i] = Input.next (); }intQuesnum = Input.nextint (); string[] Ques =NewString[quesnum]; for(inti =0; i < Quesnum; i++) {Ques[i] = Input.next (); }//Tree insertion         for(String word:strs)        {Tree.insert (word); }//Print frequency         for(String pre:ques) {System. out. println (Tree.countprefix (pre)); }    }

Results:

Hihocoder Trie Tree Java implementation

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.