Leetcode 208:implement Trie (Prefix Tree)

Source: Internet
Author: User

Implement Trie (Prefix Tree)Total Accepted: 601 Total Submissions: 2396

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

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

Ideas

Using HashMap to save children, use a bool variable to indicate if there is a word ending to this node.

[CODE]

Class Trienode {//Initialize your data structure here.    char c;    Boolean leaf;        Hashmap<character, trienode> children = new Hashmap<character, trienode> ();    Public Trienode (char c) {this.c = C; } public Trienode () {};}    public class Trie {private Trienode root;    Public Trie () {root = new Trienode ();    }//Inserts a word into the trie.        public void Insert (String word) {map<character, trienode> children = Root.children;            for (int i=0; i<word.length (); i++) {char c = word.charat (i);            Trienode T;            if (Children.containskey (c)) {T = Children.get (c);                } else {t = new Trienode (c);            Children.put (c, t);            } children = T.children;        if (I==word.length ()-1) t.leaf=true;    }}//Returns If the word is in the trie. public boolean search (String word) {Trienode t = Searchnode (Word);    return t!=null && t.leaf;    }//Returns If there is any word in the trie//that starts with the given prefix.    public boolean startsWith (String prefix) {return searchnode (prefix)! = NULL;        } private Trienode Searchnode (String word) {map<character, trienode> children = Root.children;        Trienode t = null;            for (int i=0; i<word.length (); i++) {char c = word.charat (i);            if (!children.containskey (c)) return null;            t = Children.get (c);        children = T.children;    } return t; }}//Your Trie object would be instantiated and called as such://Trie Trie = new Trie ();//Trie.insert ("somestring");//TR Ie.search ("key");





Leetcode 208:implement Trie (Prefix Tree)

Related Article

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.