LeetCode题解(0745):前缀和后缀搜索(Python)

题目:原题链接(困难)

标签:字典树

解法时间复杂度空间复杂度执行用时
Ans 1 (Python)构造 = O ( N × S 2 ) O(N×S^2) O(N×S2) ; f = O ( S ) O(S) O(S) O ( S 2 ) O(S^2) O(S2)3208ms (5.32%)
Ans 2 (Python)
Ans 3 (Python)

解法一:

class Trie:
    class _Node:
        def __init__(self):
            self.value = None
            self.weight = 0
            self.children = {}

        def __contains__(self, ch):
            return ch in self.children

        def __getitem__(self, ch):
            return self.children[ch]

        def __setitem__(self, ch, value):
            self.children[ch] = value

    def __init__(self):
        self.root = self._Node()

    def add(self, word, weight=1):
        """向字典树中添加词语"""
        node = self.root
        for ch in word:
            if ch not in node:
                node[ch] = self._Node()
            node.weight = max(node.weight, weight)
            node = node[ch]
        node.value = word
        node.weight = weight

    def __contains__(self, word):
        """判断词语是否存在"""
        node = self.root
        for ch in word:
            if ch not in node:
                return False
            node = node[ch]
        return node.value == word

    def search(self, string):
        """寻找字符串中从头开始的第1个词语(如果没有找到则返回None)"""
        node = self.root
        for ch in string:
            if ch not in node:
                return "", -1
            node = node[ch]
            if node.value is not None:
                return node.value, node.weight
        return "", -1

    def start_with(self, string):
        """寻找字符串中是否有以string开头的"""
        node = self.root
        for ch in string:
            if ch not in node:
                return "", -1
            node = node[ch]
        return node.value, node.weight


class WordFilter:

    def __init__(self, words: List[str]):
        self.trie = Trie()
        for weight, word in enumerate(words):
            code = word + "#" + word
            for i in range(len(word) + 1):
                self.trie.add(code[i:], weight=weight)

    def f(self, prefix: str, suffix: str) -> int:
        code = suffix + "#" + prefix
        return self.trie.start_with(code)[1]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

长行

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值