Easy to understand Python solution

  • 0
    class TrieNode(object):
        def __init__(self):
            self.childs = {}
            self.isWord = False
    class Trie(object):
        def __init__(self):
            self.root = TrieNode()
        def insert(self, word):
            node = self.root
            for c in word:
                node = node.childs.setdefault(c, TrieNode())
            node.isWord = True
        def search(self, word):
            node = self._searchNode(word)
            return node and node.isWord or False
        def startsWith(self, prefix):
            node = self._searchNode(prefix)
            return node is not None
        def _searchNode(self, s):
            node = self.root
            for c in s:
                if c not in node.childs:
                node = node.childs[c]
            return node

Log in to reply

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