Python Solution Beats 99.19% (Super Short)


  • 0
    P
    class Trie(object):
        def __init__(self):
            self.root = {}
    
        def insert(self, word):
            node = self.root
            word += '0'
            for c in word:
                if c not in node:
                    node[c] = {}
            
                node = node[c]  
        
        def search(self, word):
            node = self.root
            word += '0'
            for c in word:
                if c not in node:
                    return False
            
                node = node[c]           
        
            return True
        
        def startsWith(self, prefix):
            if not prefix:
                return False
        
            node = self.root
            for c in prefix:
                if c not in node:
                    return False
            
                node = node[c]  
    
            return True

Log in to reply
 

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