<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>prefix tree Archives - Huahua&#039;s Tech Road</title>
	<atom:link href="https://zxi.mytechroad.com/blog/tag/prefix-tree/feed/" rel="self" type="application/rss+xml" />
	<link>https://zxi.mytechroad.com/blog/tag/prefix-tree/</link>
	<description></description>
	<lastBuildDate>Thu, 19 Apr 2018 15:27:46 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.0.8</generator>

<image>
	<url>https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/cropped-photo-32x32.jpg</url>
	<title>prefix tree Archives - Huahua&#039;s Tech Road</title>
	<link>https://zxi.mytechroad.com/blog/tag/prefix-tree/</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>花花酱 LeetCode 208. Implement Trie (Prefix Tree)</title>
		<link>https://zxi.mytechroad.com/blog/data-structure/leetcode-208-implement-trie-prefix-tree/</link>
					<comments>https://zxi.mytechroad.com/blog/data-structure/leetcode-208-implement-trie-prefix-tree/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Thu, 28 Sep 2017 05:23:38 +0000</pubDate>
				<category><![CDATA[Data Structure]]></category>
		<category><![CDATA[children]]></category>
		<category><![CDATA[hashtable]]></category>
		<category><![CDATA[prefix]]></category>
		<category><![CDATA[prefix tree]]></category>
		<category><![CDATA[trie]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=440</guid>

					<description><![CDATA[<p>Problem: Implement a trie with insert, search, and startsWith methods. Note: You may assume that all inputs are consist of lowercase letters a-z. Idea: Tree/children array &#160; &#160; Solution: C++&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/data-structure/leetcode-208-implement-trie-prefix-tree/">花花酱 LeetCode 208. Implement Trie (Prefix Tree)</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p><iframe width="500" height="375" src="https://www.youtube.com/embed/f48wGD-MuQw?feature=oembed" frameborder="0" gesture="media" allowfullscreen></iframe></p>
<p><strong>Problem:</strong></p>
<p>Implement a trie with <code>insert</code>, <code>search</code>, and <code>startsWith</code> methods.</p>
<p><b>Note:</b><br />
You may assume that all inputs are consist of lowercase letters <code>a-z</code>.</p>
<p><strong>Idea:</strong></p>
<p><script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script><br />
<ins class="adsbygoogle"
     style="display:block; text-align:center;"
     data-ad-layout="in-article"
     data-ad-format="fluid"
     data-ad-client="ca-pub-2404451723245401"
     data-ad-slot="7983117522"></ins><br />
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script><br />
Tree/children array</p>
<p><a href="http://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/208-ep74-1.png"><img class="alignnone size-full wp-image-445" src="http://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/208-ep74-1.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/208-ep74-1.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/208-ep74-1-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/208-ep74-1-768x432.png 768w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/208-ep74-1-624x351.png 624w" sizes="(max-width: 960px) 100vw, 960px" /></a></p>
<p>&nbsp;</p>
<p><a href="http://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/208-ep74-2.png"><img class="alignnone size-full wp-image-444" src="http://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/208-ep74-2.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/208-ep74-2.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/208-ep74-2-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/208-ep74-2-768x432.png 768w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/208-ep74-2-624x351.png 624w" sizes="(max-width: 960px) 100vw, 960px" /></a></p>
<p>&nbsp;</p>
<p><strong>Solution:</strong></p>
<p>C++ / Array</p><pre class="crayon-plain-tag">// Author: Huahua 
// Running time: 99 ms
class Trie {
public:
    /** Initialize your data structure here. */
    Trie(): root_(new TrieNode()) {}
    
    /** Inserts a word into the trie. */
    void insert(const string&amp; word) {
        TrieNode* p = root_.get();
        for (const char c : word) {
            if (!p-&gt;children[c - 'a'])
                p-&gt;children[c - 'a'] = new TrieNode();
            p = p-&gt;children[c - 'a'];
        }
        p-&gt;is_word = true;
    }
    
    /** Returns if the word is in the trie. */
    bool search(const string&amp; word) const {
        const TrieNode* p = find(word);
        return p &amp;&amp; p-&gt;is_word;
    }
    
    /** Returns if there is any word in the trie that starts with the given prefix. */
    bool startsWith(const string&amp; prefix) const {
        return find(prefix) != nullptr;
    }
private:
    struct TrieNode {
        TrieNode():is_word(false), children(26, nullptr){}
        
        ~TrieNode() {
            for (TrieNode* child : children)
                if (child) delete child;
        }
               
        bool is_word;
        vector&lt;TrieNode*&gt; children;
    };
    
    const TrieNode* find(const string&amp; prefix) const {
        const TrieNode* p = root_.get();
        for (const char c : prefix) {
            p = p-&gt;children[c - 'a'];
            if (p == nullptr) break;
        }
        return p;
    }
    
    std::unique_ptr&lt;TrieNode&gt; root_;
};</pre><p>&nbsp;</p>
<p>C++ / hashmap</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 98 ms
class Trie {
public:
    /** Initialize your data structure here. */
    Trie(): root_(new TrieNode()) {}
    
    /** Inserts a word into the trie. */
    void insert(const string&amp; word) {
        TrieNode* p = root_.get();
        for (const char c : word) {
            if (!p-&gt;children.count(c))
                p-&gt;children[c] = new TrieNode();
            p = p-&gt;children[c];
        }
        p-&gt;is_word = true;
    }
    
    /** Returns if the word is in the trie. */
    bool search(const string&amp; word) const {
        const TrieNode* p = find(word);
        return p &amp;&amp; p-&gt;is_word;
    }
    
    /** Returns if there is any word in the trie that starts with the given prefix. */
    bool startsWith(const string&amp; prefix) const {
        return find(prefix) != nullptr;
    }
private:
    struct TrieNode {
        TrieNode():is_word(false){}
        
        ~TrieNode() {
            for (auto&amp; kv : children)
                if (kv.second) delete kv.second;
        }
        
        bool is_word;
        unordered_map&lt;char, TrieNode*&gt; children;
    };
    
    const TrieNode* find(const string&amp; prefix) const {
        const TrieNode* p = root_.get();
        for (const char c : prefix) {
            if (!p-&gt;children.count(c)) return nullptr;
            p = p-&gt;children.at(c);
        }
        return p;
    }
    
    std::unique_ptr&lt;TrieNode&gt; root_;
};</pre><p>&nbsp;</p>
<p>Java</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 184 ms
class Trie {
    class TrieNode {
        public TrieNode() {
            children = new TrieNode[26];
            is_word = false;
        }
        public boolean is_word;
        public TrieNode[] children;
    }
    
    private TrieNode root;
    
    /** Initialize your data structure here. */
    public Trie() {
        root = new TrieNode();
    }
    
    /** Inserts a word into the trie. */
    public void insert(String word) {
        TrieNode p = root;
        for (int i = 0; i &lt; word.length(); i++) {
            int index = (int)(word.charAt(i) - 'a');
            if (p.children[index] == null)
                p.children[index] = new TrieNode();
            p = p.children[index];
        }
        p.is_word = true;
    }
    
    /** Returns if the word is in the trie. */
    public boolean search(String word) {
        TrieNode node = find(word);
        return node != null &amp;&amp; node.is_word;
    }
    
    /** Returns if there is any word in the trie that starts with the given prefix. */
    public boolean startsWith(String prefix) {
        TrieNode node = find(prefix);
        return node != null;
    }
    
    private TrieNode find(String prefix) {
        TrieNode p = root;
        for(int i = 0; i &lt; prefix.length(); i++) {
            int index = (int)(prefix.charAt(i) - 'a');
            if (p.children[index] == null) return null;
            p = p.children[index];
        }
        return p;
    }
}</pre><p>&nbsp;</p>
<p>Python 1:</p><pre class="crayon-plain-tag">"""
Author: Huahua
Running time: 469 ms
"""
class Trie(object):
    class TrieNode(object):
        def __init__(self):
            self.is_word = False
            self.children = [None] * 26
        
    def __init__(self):
        self.root = Trie.TrieNode()
        

    def insert(self, word):
        p = self.root
        for c in word:
            index = ord(c) - ord('a')
            if not p.children[index]: 
                p.children[index] = Trie.TrieNode()
            p = p.children[index]
        p.is_word = True

    def search(self, word):
        node = self.find(word)
        return node is not None and node.is_word
        

    def startsWith(self, prefix):
        return self.find(prefix) is not None
    
    def find(self, prefix):
        p = self.root
        for c in prefix:
            index = ord(c) - ord('a')
            if not p.children[index]: return None
            p = p.children[index]
        return p</pre><p>&nbsp;</p>
<p>Python 2:</p><pre class="crayon-plain-tag">"""
Author: Huahua
Running time: 212 ms
"""
class Trie(object):            
    def __init__(self):
        self.root = {}
        

    def insert(self, word):
        p = self.root
        for c in word:            
            if c not in p: 
                p[c] = {}
            p = p[c]
        p['#'] = True

    def search(self, word):
        node = self.find(word)
        return node is not None and '#' in node
        

    def startsWith(self, prefix):
        return self.find(prefix) is not None
    
    def find(self, prefix):
        p = self.root
        for c in prefix:            
            if c not in p: return None
            p = p[c]
        return p</pre><p>&nbsp;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/data-structure/leetcode-208-implement-trie-prefix-tree/">花花酱 LeetCode 208. Implement Trie (Prefix Tree)</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/data-structure/leetcode-208-implement-trie-prefix-tree/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
