Implementing a Trie to support autocomplete in Python

后端 未结 2 845
無奈伤痛
無奈伤痛 2021-02-04 17:50

I\'m trying to implement a data structure that supports autocomplete on a website. I\'ve managed to implement an iterative version of a Trie. It supports the two primary methods

2条回答
  •  不思量自难忘°
    2021-02-04 18:19

    class Trie:
    
        def __init__(self):
            """
            Initialize your data structure here.
            """
            self.root = {}
            self.end = "#"
    
        def words_with_prefix(self, prefix: str):
            '''
            return all possible words with common prefix
            '''
            node = self.root
            for c in prefix:
                if c not in node:
                    return []
                node = node[c]
            ans = []
            self._words_with_prefix_helper(node, prefix, ans)
            return ans
    
        def _words_with_prefix_helper(self, node, prefix, ans):
            for k in node:
                if k == self.end:
                    ans.append(prefix)
                    continue
                self._words_with_prefix_helper(node[k], prefix + k, ans)
    

    complete implementation

提交回复
热议问题