Python using dict only (beat 90%)


  • 0
    K

    Just like most of the Python solutions here where dictionary is used in implementation, except determining if an input is a word in the trie is done by an empty string ``, a key in the dictionary of the last node. Some space can be saved from those prefix nodes.

    class Trie(object):
        t={}
        def __init__(self):
            self.t={}
            
    
        def insert(self, word):
      
            a=self.t
            for i in word:
                if i not in a:
                    a[i]={}
                a=a[i]
            a[""]={}
                    
    
        def search(self, word):
            a=self.t
            for i in word:
                if i not in a:
                    return False
                a=a[i]
            if "" in a: return True
            else: return False
            
    
        def startsWith(self, prefix):
            a=self.t
            for i in prefix:
                if i not in a:
                    return False
                a=a[i]
            return True
    
    

Log in to reply
 

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