Suffix Trie Construction

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

Problem statement

Suffix Trie Construction

 

 Example

Suffix Trie Construction

 

 Analysis

step 1

Suffix Trie Construction

 

 step 2

Suffix Trie Construction

 

 step 3

Suffix Trie Construction

 

 Time/ Space Complexity

Suffix Trie Construction

 

 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 
        
        

 

 
上一篇:后缀树(Suffix Tree)


下一篇:python 获取文件后缀名的方法