Golang solution (165 ms)


  • 0
    N
    type Trie struct {
    	children []*Trie
    	isLeaf bool
    }
    
    func charToIndex(c uint8) uint8 {
    	return c - 'a'
    }
    
    
    /** Initialize your data structure here. */
    func Constructor() Trie {
    	return Trie{children: make([]*Trie, 26), isLeaf: false}
    }
    
    
    /** Inserts a word into the trie. */
    func (this *Trie) Insert(word string)  {
    	curNode := this
    	for i := 0; i < len(word); i++ {
    		if curNode.children[charToIndex(word[i])] == nil {
    			t := Constructor()
    			curNode.children[word[i] - 'a'] = &t
    		}
    		curNode = curNode.children[charToIndex(word[i])]
    	}
    	curNode.isLeaf = true
    }
    
    
    /** Returns if the word is in the trie. */
    func (this *Trie) Search(word string) bool {
    	curNode := this
    	for i := 0; i < len(word); i++ {
    		if curNode.children[charToIndex(word[i])] == nil {
    			return false
    		}
    		curNode = curNode.children[charToIndex(word[i])]
    	}
    	return curNode.isLeaf
    }
    
    
    /** Returns if there is any word in the trie that starts with the given prefix. */
    func (this *Trie) StartsWith(prefix string) bool {
    	curNode := this
    	for i := 0; i < len(prefix); i++ {
    		if curNode.children[charToIndex(prefix[i])] == nil {
    			return false
    		}
    		curNode = curNode.children[charToIndex(prefix[i])]
    	}
    	return true
    }
    

Log in to reply
 

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