Implement Trie (Prefix Tree)


#1

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

Example:

Trie trie = new Trie();

trie.insert("apple");
trie.search("apple");   // returns true
trie.search("app");     // returns false
trie.startsWith("app"); // returns true
trie.insert("app");   
trie.search("app");     // returns true

Note:

  • You may assume that all inputs are consist of lowercase letters a-z.
  • All inputs are guaranteed to be non-empty strings.

#2

Uses a trie node which has a character, boolean value to tell if it is a end of a word and references to the children.

type Node struct{
    char rune
    isWord bool
    children []*Node
}

type Trie struct {
    root *Node
}


/** Initialize your data structure here. */
func Constructor() Trie {
    node := &Node{char : ' ', isWord: false, children : make([]*Node, 26)}
    return Trie{root: node}
}


/** Inserts a word into the trie. */
func (this *Trie) Insert(word string)  {
    temp := this.root
    for _, ch := range word {
        if temp.children[ch-'a']==nil{
            temp.children[ch-'a'] = &Node{char : ch, children : make([]*Node, 26)}
            temp = temp.children[ch-'a']
        } else {
            temp = temp.children[ch-'a']
        }
    }
    temp.isWord = true
}


/** Returns if the word is in the trie. */
func (this *Trie) Search(word string) bool {
    temp := this.root
    for _, ch := range word{
        if temp.children[ch-'a']==nil{
            return false
        }
        temp = temp.children[ch-'a']
    }
    return temp.isWord
}


/** Returns if there is any word in the trie that starts with the given prefix. */
func (this *Trie) StartsWith(prefix string) bool {
   temp := this.root
    for _, ch := range prefix{
        if temp.children[ch-'a']==nil{
            return false
        }
        temp = temp.children[ch-'a']
    }
    return true
}


/**
 * Your Trie object will be instantiated and called as such:
 * obj := Constructor();
 * obj.Insert(word);
 * param_2 := obj.Search(word);
 * param_3 := obj.StartsWith(prefix);
 */