leetcode No208. Implement Trie (Prefix Tree)

Posted Dufre.WC

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode No208. Implement Trie (Prefix Tree)相关的知识,希望对你有一定的参考价值。

Welcome to Github- LeetCode

Solution

The data structure Trie (Prefix tree)

You can see 《Algorithm》 Chapter 5.2 Tries

  • bool isWord whether the node corresponds to the end of the key, or is just a key prefix.
  • Trie* childNode[26] Maximum of R links to its children, where each link corresponds to one of R character values from dataset alphabet. In this case, R is 26

This is LeetCode Solution:
Solution

Code

C++

class Trie 
public:
    /** Initialize your data structure here. */
    Trie() 
        
    
    
    /** Inserts a word into the trie. */
    void insert(string word) 
        Trie* cur = this;
        for(int i=0; i<word.size(); i++)
            int index = word[i]-'a';
            if(cur->childNode[index] == NULL)
                cur->childNode[index] = new Trie();
            
            cur = cur->childNode[index];
        
        cur->isWord = true;
    
    
    /** Returns if the word is in the trie. */
    bool search(string word) 
        Trie* cur = this;
        for(int i=0; i<word.size(); i++)
            int index = word[i]-'a';
            if(cur->childNode[index] == NULL)
                return false;
            else
                cur = cur->childNode[index];    
            
        
        return cur->isWord;
    
    
    /** Returns if there is any word in the trie that starts with the given prefix. */
    bool startsWith(string prefix) 
        Trie* cur = this;
        for(int i=0; i<prefix.size(); i++)
            int index = prefix[i]-'a';
            if(cur->childNode[index] == NULL)
                return false;
            else
                cur = cur->childNode[index];    
            
        
        return true;
    
private:
    bool isWord = false;
    Trie* childNode[26] = ;
;

/**
 * Your Trie object will be instantiated and called as such:
 * Trie* obj = new Trie();
 * obj->insert(word);
 * bool param_2 = obj->search(word);
 * bool param_3 = obj->startsWith(prefix);
 */

Java

Refer to LeetCode Solution

class TrieNode
    private TrieNode[] links;
    private final int R = 26;
    private boolean isEnd;
    
    public TrieNode()
        links = new TrieNode[R];
    
    
    public boolean isContainsKey(char c)
        return links[c-'a'] != null;
    
    
    public TrieNode get(char ch)
        return links[ch-'a'];
    
    
    public void put(char ch, TrieNode node)
        links[ch-'a'] = node;
    
    public void setEnd()
        isEnd = true;
    
    public boolean isEnd()
        return isEnd;
    


class Trie 
    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 cur = root;
        for(int i=0;i<word.length();i++)
            char curLetter = word.charAt(i);
            if(!cur.isContainsKey(curLetter))
                cur.put(curLetter, new TrieNode());
            
            cur = cur.get(curLetter);
        
        cur.setEnd();
    
    
    /** Returns if the word is in the trie. */
    public boolean search(String word) 
        TrieNode cur = root;
        for(int i=0;i<word.length();i++)
            char curLetter = word.charAt(i);
            if(!cur.isContainsKey(curLetter))
                return false;
            
            cur = cur.get(curLetter);
        
        return cur.isEnd();
    
    
    /** Returns if there is any word in the trie that starts with the given prefix. */
    public boolean startsWith(String prefix) 
        TrieNode cur = root;
        for(int i=0;i<prefix.length();i++)
            char curLetter = prefix.charAt(i);
            if(!cur.isContainsKey(curLetter))
                return false;
            
            cur = cur.get(curLetter);
        
        return true;
    


/**
 * Your Trie object will be instantiated and called as such:
 * Trie obj = new Trie();
 * obj.insert(word);
 * boolean param_2 = obj.search(word);
 * boolean param_3 = obj.startsWith(prefix);
 */

Python

class TrieNode:
        def __init__(self):
            self.child = collections.defaultdict(TrieNode)
            self.isWord = False

class Trie:
    

    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.root = TrieNode()
        

    def insert(self, word) -> bool:
        """
        Inserts a word into the trie.
        :type word: str
        :rtype: void
        """
        cur = self.root
        for c in word:
            cur = cur.child[c]
        cur.isWord = True
        

    def search(self, word):
        """
        Returns if the word is in the trie.
        :type word: str
        :rtype: bool
        """
        cur = self.root
        for c in word:
            cur = cur.child.get(c)
            if cur is None:
                return False
            
        return cur.isWord
        

    def startsWith(self, prefix):
        """
        Returns if there is any word in the trie that starts with the given prefix.
        :type prefix: str
        :rtype: bool
        """
        cur = self.root
        for c in prefix:
            cur = cur.child.get(c)
            if cur is None:
                return False
            
        return True
        


# Your Trie object will be instantiated and called as such:
# obj = Trie()
# obj.insert(word)
# param_2 = obj.search(word)
# param_3 = obj.startsWith(prefix)

# collections.defaultdict is like a dict, but is instantiated with a type

collections.defaultdict is like a dict, but is instantiated with a type,
You can see defaultdict

以上是关于leetcode No208. Implement Trie (Prefix Tree)的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 208. Implement Trie (Prefix Tree)

[LeetCode] 208. Implement Trie (Prefix Tree)

[LeetCode] 208(LintCode). Implement Trie(Prefix Tree)

LeetCode 208. Implement Trie (Prefix Tree)

[LeetCode] 208. Implement Trie (Prefix Tree) Java

LeetCode 208. Implement Trie (Prefix Tree)