Golang solution (168ms) - using maps instead byte arrays


  • 0
    type Trie struct {
        children map[byte]*Trie
        eow bool
    }
    
    func Constructor() Trie {
        return Trie{children: map[byte]*Trie{}, eow: false}
    }
    
    func (t *Trie) Insert(word string)  {
        for i := 0; i < len(word); i++ {
            node, ok := t.children[word[i]]
            if !ok {
                node = &Trie{
                    children: map[byte]*Trie{}, eow: false,
                }
                t.children[word[i]] = node
            }
            t = node
        }
        t.eow = true
    }
    
    func (t *Trie) Search(word string) bool {
        for i := 0; i < len(word); i++ {
            node, ok := t.children[word[i]]
            if !ok { return false }
            t = node
        }
        return t.eow
    }
    
    func (t *Trie) StartsWith(prefix string) bool {
        for i := 0; i < len(prefix); i++ {
            node, ok := t.children[prefix[i]]
            if !ok { return false }
            t = node
        }
        return true
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.