No Prefix Set

  • + 0 comments

    be careful with the limit memory, can not do manual way, only with trie on python

    class TrieNode:
        def __init__(self):
            self.children = {}
            self.is_end_of_word = False
    
    class Trie:
        def __init__(self):
            self.root = TrieNode()
        
        def insert(self, word):
            node = self.root
            for char in word:
                if char not in node.children:
                    node.children[char] = TrieNode()
                node = node.children[char]
                # If we reach a node that is the end of another word, it's a BAD SET
                if node.is_end_of_word:
                    return False
            # Mark the end of this word
            node.is_end_of_word = True
            # If this word is a prefix of any existing word, it's a BAD SET
            if node.children:
                return False
            return True
    
    def noPrefix(words):
        trie = Trie()
        for word in words:
            if not trie.insert(word):
                print("BAD SET")
                print(word)
                return
        print("GOOD SET")