【算法】字典树


class TrieNode:
    def __init__(self, c=None):
        self.val = c
        self.children = [None] * 26


class Trie:
    def __init__(self):
        self.root = TrieNode()
        self.new_words = 0

    def insert(self, word):
        cur = self.root
        is_new_word = False
        for j in range(len(word) - 1, -1, -1):
            c = word[j]
            if cur.children[ord(c) - ord('a')] is None:
                is_new_word = True
                cur.children[ord(c) - ord('a')] = TrieNode(c)
            cur = cur.children[ord(c) - ord('a')]
        return len(word) + 1 if is_new_word is True else 0