Python Тр ie реализация - PullRequest
       9

Python Тр ie реализация

0 голосов
/ 15 марта 2020

Я работаю над вопросом о парах палиндромов в leetcode. (Нет: 336, если кому-то интересно). Я пытаюсь понять реализацию tr ie для python. Следуя этому примеру (это полностью функциональный код) https://fizzbuzzed.com/top-interview-questions-5/

Я не могу понять метод add. У меня есть понимание того, что происходит, но я не знаю, как это происходит.


class Trie:

    def __init__(self):
        # letter -> next trie node.
        self.paths = defaultdict(Trie)
        # If a word ends at this node, then this will be a positive value
        # that indicates the location of the word in the input list.
        self.wordEndIndex = -1
        # Stores all words that are palindromes from this node to end of word.
        # e.g. if we are on a path 'a','c' and word "babca" exists in this trie
        # (words are added in reverse), then "acbab"'s index will be in this
        # list since "bab" is a palindrome.
        self.palindromesBelow = []

    # Adds a word to the trie - the word will be added in 
    # reverse (e.g. adding abcd adds the path d,c,b,a,$index) to the trie.
    # word - string the word to be added
    # index - int index of the word in the list, used as word identifier.
    def addWord(self, word, index):
        trie = self
        for j, char in enumerate(reversed(word)): 
            if isPalindrome(word[0:len(word)-j]): **#ignore this part**
                trie.palindromesBelow.append(index) **#ignore this part**
            trie = trie.paths[char] **#this is the line I do not follow**
        trie.wordEndIndex = index

Почему мы добавляем пустой узел tr ie (defaultdict (Tr ie)) обратно в самостоятельно (Trie = сам). Как мы узнаем, каким будет следующий символ в письме, когда мы просто добавим обратно к себе?

Может кто-нибудь объяснить поток для [bat, cat]. Любая помощь будет высоко ценится.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...