Leetcode 208Implement Trie (Prefix Tree)

Source: Internet
Author: User

Implement a trie with insert , search , and startsWith methods.

Note:
You may assume this all inputs is consist of lowercase letters a-z .

Building a dictionary Tree

classTrienode {CharC; HashMap<character, trienode> children=NewHashmap<character, trienode>(); BooleanHasword;  PublicTrienode () {} PublicTrienode (Charc) {         This. c=C; }} Public classtrie{PrivateTrienode Root;  PublicTrie () {root=NewTrienode (); }         Public voidInsert (String word) {Trienode cur=Root; HashMap<character, trienode> curchildren=Root.children; Char[] wordarray=Word.tochararray ();  for(inti=0;i<wordarray.length;i++){            CharWc=Wordarray[i]; if(Curchildren.containskey (WC)) {cur=curchildren.get (WC); }Else{Trienode NewNode=NewTrienode (WC);                Curchildren.put (WC, newNode); Cur=NewNode; } Curchildren=Cur.children; if(i==wordarray.length-1) {Cur.hasword=true; }        }    }         Public BooleanSearch (String word) {if(Searchwordnodepos (word) = =NULL){            return false; }Else if(Searchwordnodepos (Word). Hasword) {return true; }Else return false; }         Public BooleanstartsWith (String prefix) {if(Searchwordnodepos (prefix) = =NULL){            return false; }Else return true; }    PrivateTrienode Searchwordnodepos (String s) {//TODO auto-generated Method StubHashmap<character, trienode> children=Root.children; Trienode cur=NULL; Char[] sarray=S.tochararray ();  for(inti=0;i<sarray.length;i++){            CharC=Sarray[i]; if(Children.containskey (c)) {cur=Children.get (c); Children=Cur.children; }Else{                return NULL; }        }                returncur; }            }//Your Trie object would be instantiated and called as such://Trie Trie = new Trie ();//Trie.insert ("somestring");//trie.search ("key");
View Code

Reference: http://blog.csdn.net/yangliuy/article/details/46287671

Http://www.cnblogs.com/huangxincheng/archive/2012/11/25/2788268.html

Leetcode 208Implement Trie (Prefix Tree)

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.