AC Python Solution


  • 39
    T
    class TrieNode:
    # Initialize your data structure here.
    def __init__(self):
        self.children = collections.defaultdict(TrieNode)
        self.is_word = False
    
    class Trie:
    
    def __init__(self):
        self.root = TrieNode()
    
    def insert(self, word):
        current = self.root
        for letter in word:
            current = current.children[letter]
        current.is_word = True
    
    def search(self, word):
        current = self.root
        for letter in word:
            current = current.children.get(letter)
            if current is None:
                return False
        return current.is_word
    
    def startsWith(self, prefix):
        current = self.root
        for letter in prefix:
            current = current.children.get(letter)
            if current is None:
                return False
        return True

  • 0
    W

    @tusizi

    A brilliant clean Python solution. Thanks!


  • 0
    A

    Great Solution!


  • 0
    S

    How do you implement delete(self, word) in this code?


  • 0
    M

    @svkrish24 How about this?

    def delete(self, word):
        if not self.search(word):
            return False
        current = self.root
        for letter in word:
            if len(current.children) == 1:
                del current.children[letter]
                return True
            current = current.children.get(letter)
        return True
            
    
                        
        
    

  • 0
    S

    @martingale This doesn't work. If we have words "when" and "what" in the trie, you code will delete both the words when we try to delete either.


  • 0
    S
    This post is deleted!

Log in to reply
 

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