其他分享
首页 > 其他分享> > Suffix Trie Construction

Suffix Trie Construction

作者:互联网

refer to: https://www.algoexpert.io/questions/Suffix%20Trie%20Construction

Problem statement

 

 Example

 

 Analysis

step 1

 

 step 2

 

 step 3

 

 Time/ Space Complexity

 

 Code

class SuffixTrie:
    def __init__(self, string):
        self.root = {}
        self.endSymbol = "*"
        self.populateSuffixTrieFrom(string)

    # creation function
    def populateSuffixTrieFrom(self, string):
        for i in range(len(string)):
            self.insertSubstringStartingAt(i, string)

    def insertSubstringStartingAt(self, i, string):
        node = self.root
        for j in range(i, len(string)):
            letter = string[j]
            if letter not in node:
                node[letter] = {} # create an empty hashmap
            node = node[letter] # update the currect node
        node[self.endSymbol] = True # after iterate one whole string, add * at the end
        
    #search function
    def contains(self, string):
        node = self.root
        for letter in string:
            if letter not in node:
                return False
            node = node[letter]# if letter in node, keep down traversing the suffix tree
        return self.endSymbol in node # avoid some cases that a string has not been traversed totally 
        
        

 

 

标签:node,Suffix,Trie,self,endSymbol,Construction,letter,def,string
来源: https://www.cnblogs.com/LilyLiya/p/14824375.html