Java Implementation Dictionary Tree Trietree__java

Source: Internet
Author: User

In order to prepare Ali's online written examination, these days reviewed the data structure. When I saw the dictionary tree, I suddenly found that the high-frequency words of level 46 could be found by the dictionary tree. (should not be a number of the bar ...)

The process of constructing a dictionary tree is as follows:

1. First determine how the tree node needs to use the data structure, I wrote:

public class Trietreenode {
	/**
	 * Node Depth */public short
	depth;
	/**
	 * Holds all child nodes of the current node/public
	Map<integer, trietreenode> children = new Hashmap<integer, Trietreenode> ();
	/**
	 * Is the end of the word * * Public
	Boolean istail = false;
	/**
	 * Parents node * * Public
	trietreenode parent;
	/**
	 * Can be any letter in a-
	 z
	/public char value;
	/**
	 * When the word is the same, wordcount++, used to calculate the same number of words
	 * * public
	int wordCount = 0;
	/**
	 * Store a whole word
	/public StringBuilder word = new StringBuilder ();

	Public Trietreenode () {
		//TODO auto-generated constructor stub
	}

}
2. Connect the nodes by the Parent,children properties of the nodes. Each word starts with the root node as the parent node, each character in the word constructs a child node, or if the child node exists, it is used directly, otherwise it is new.

	/** * Creates a dictionary tree with a given string, temporarily supports only English * @param data The string used to create the dictionary tree, and does not support Chinese.
		*/public void Createtrietree (String data) {//string[word in text] Strarr = Data.split (regex); Create the root node of the dictionary tree//read the split str array into the dictionary tree for (String S:strarr) {//single letter without considering if (S.length () > 1) {///Every Word starts, all in
				Root as the first parent node trietreenode parent = root;
					Start looping each word for (short i = 0; i < s.length (); i++) {char c = s.charat (i);
					Uppercase is not considered here, just lowercase.
					c = (char) (C < ' a '? C + 32:c);
					Create child nodes Trietreenode = Createchildtrietree (c, I, parent);
					int key = Child.value * + child.depth;
					Parent.children.put (key, child);
				parent = child;
				The last node is used as the tail after each word is cycled.
				Parent.istail = true;
				Each encounter the same word will wordcount++ int wordCount = ++parent.wordcount;
				String Word = parent.word.toString ();
			Place the number of words and words into the map wordcountmap.put (Word, new wordandcount (Word, wordCount)); /** * is used to create child nodes * @param c * @param depth * @pAram Parent * @return/private Trietreenode Createchildtrietree (char c, short depth, trietreenode parent) {//
		By the parent node, the depth of the number and the character c,3 a condition to determine whether the child node already exists, if it exists, to obtain it directly.
		Trietreenode child = Getchild (c, depth, parent);
		If it does not exist, create a new one and assign the parameter to it.

			if (child = = null) {child = new Trietreenode ();
			child.depth = depth;
			Child.parent = parent;
			Child.value = C;
			Used to save words, through the istail of the match, you can save the search word process.
		Child.word.append (Parent.word). append (c);
	return to child;
	 /** * Gets child nodes based on the character C, tree depth, and parent node. * @param c * @param depth * @param parent * @return/private Trietreenode Getchild (char c, short depth, trietre
		Enode parent) {//TODO auto-generated Method Stub//each parent node, there is a hashmap to hold all the child nodes, the key is based on C and depth to synthesize.
		Map<integer, trietreenode> children = Parent.children;
		Because the depth of the dictionary tree is not more than 26, so 10 bits and a bit let depth to store, hundreds of above let the character C to store, this can constitute a unique key to correspond to a value int key = c * + depth;
	return Children.get (key); }

3. The dictionary tree has been constructed with the above steps. Next is the read value, through Maker.getwordcountmap (), you can get all the words and the number of occurrences. If you want to sort the display, You can call the sort method in Trietreemaker for sorting. If there is a more specific requirement, the root node can be obtained by getting method and recursively traversed.


Finally, attach the test code and data:

 @Test public void Test () {String FilePath = "C:\\logs\\file.log";

		File Srcfile = new file (FilePath);

		System.out.println ("File Size:" + srcfile.length ()/1024/1024.0 + "M");

		Long End2, end, start = System.nanotime ();

		Trietreemaker maker = new Trietreemaker ();
		Maker.setcapacity (1024 * 1024 * 20);
		The dictionary tree is constructed from a given file, or it can be implemented by calling Createtrietree ("xxxx").

		Maker.obtaindataandcreatetrietree (Srcfile);

		End = System.nanotime ();
		System.out.println ("After creation is accomplished:" + bigdecimal.valueof (End-start, 9)); True to represent ascending, false for descending list<entry<string, wordandcount>> List = Maker.sort (Maker.getwordcountmap (), True)

		;

		End2 = System.nanotime ();
		System.out.println ("After the Sort is accomplished:" + bigdecimal.valueof (end2-end, 9)); Results output for (entry<string, wordandcount> entry:list) {System.out.println (Entry.getvalue (). Word + ":" + E
		Ntry.getvalue (). Count); }
	}
File size:15.6962890625m
After creation is accomplished:2.812941204s
After the Sort is accomplished:0.004912021s
org:113792
java:74116
at:71064
springframework:68740
security:62020
web:53172
apache:37100
struts:33516
.... Because the result is too much, omit.

Click here to download the source

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.