leetcode_Others

思路:
用例如:
# big = "abcd"
# smalls = ["a","abc"]
字典树结构:
trie.root = {"a": Node_0xx}
                  Node.word_idx = 0   # 第1个单词
                  Node.word_end = True
                    \
                    {"b": Node_0xx}
                          Node.word_end = False
                          # 不是叶子没有word_idx省内存呵呵
                              \
                            {"c": Node_0xx}
                                  Node.word_idx = 1  # 第2个单词
                                  Node.word_end = True
class Node(object):
    # 节点
    def __init__(self):
        self.dic = {}
        self.word_end = False
        # self.word_idx = None # 挂在单词最后一个字符节点上

class Trie(object):
    def __init__(self):
        self.root = {}
    def insert_word(self, word, idx):
        # 空word ""
        if word=="" : return
        cur_dic = self.root
        for char in word:
            cur_dic.setdefault(char, Node())
            ob = cur_dic[char]
            cur_dic = ob.dic
        ob.word_end = True
        ob.word_idx = idx


class Solution:
    def multiSearch(self, big, smalls):
        self.build_tree(smalls)
        rt = [[] for _ in range(len(smalls))]
        for i in range(len(big)):
            cur = self.trie.root
            for j in range(i, len(big)):
            # for location, char in enumerate(big[i:]):
                if big[j] in cur:
                    ob = cur[big[j] ]
                    # _idx = ob.word_idx
                    _end = ob.word_end
                    cur = ob.dic
                    if _end: rt[ob.word_idx].append(i)
                else: break
        return rt

    def build_tree(self, smalls):
        self.trie = Trie()
        for idx, word in enumerate(smalls):
            self.trie.insert_word(word, idx)


s = Solution()
big = "mississippi"
smalls = ["is","ppi","hi","sis","i","ssippi"]
# big = "abcd"
# smalls = ["a","ab"]
print(s.multiSearch(big, smalls))
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值