Leetcode 3093. Longest Common Suffix Queries

  • [Leetcode 3093. Longest Common Suffix Queries](#Leetcode 3093. Longest Common Suffix Queries)
    • [1. 解题思路](#1. 解题思路)
    • [2. 代码实现](#2. 代码实现)

1. 解题思路

这一题的话思路上其实就是一个Trie树的变体。

对于每一个wordsQuery当中的word,我们要在wordsContainer当中获取答案,我们只需要将wordsContainer构建成一个Trie树,就能够快速地获得我们所需的答案了。

具体关于Trie树的内容,我们之前已经写过一个博客(经典算法:Trie树结构简介)对其进行过介绍了,这里我们就不赘述了,唯一需要注意的是,这里由于我们不是完全匹配单词,而是匹配最长公共suffix,因此我们需要做一些变体,具体来说就是在trie树的每一个节点都记录下该节点对应的单词。

此外,由于相同suffix的单词需要有一定的顺序关系,因此,我们在加入Trie树时需要对每一个节点的单词进行一下顺序的考察,对此,我们的处理方式是提前进行一下排序即可。

2. 代码实现

给出python代码实现如下:

python 复制代码
class Trie:
    def __init__(self):
        self.trie = {}
        self.init = -1
    
    def add_word(self, word, idx):
        trie = self.trie
        if self.init == -1:
            self.init = idx
        for c in word:
            _, trie = trie.setdefault(c, (idx, {}))
        return

    def find(self, word):
        trie = self.trie
        ans = self.init
        for c in word:
            if c not in trie:
                break
            ans, trie = trie[c]
        return ans

class Solution:
    def stringIndices(self, wordsContainer: List[str], wordsQuery: List[str]) -> List[int]:
        words = [(len(w), i, w) for i, w in enumerate(wordsContainer)]
        words = sorted(words)
        
        trie = Trie()
        for _, i, word in words:
            trie.add_word(word[::-1], i)

        ans = [trie.find(word[::-1]) for word in wordsQuery]
        return ans

提交代码评测得到:耗时1197ms,占用内存144.7MB。

相关推荐
Espresso Macchiato2 个月前
Leetcode 3261. Count Substrings That Satisfy K-Constraint II
滑动窗口·leetcode hard·leetcode周赛411·leetcode 3261·累积数组
Espresso Macchiato2 个月前
Leetcode 3260. Find the Largest Palindrome Divisible by K
leetcode hard·回文·分类讨论·leetcode 3260·leetcode周赛411
神探阿航3 个月前
数据结构——Trie
数据结构·c++·算法·字典树·trie
Espresso Macchiato3 个月前
Leetcode 3213. Construct String with Minimum Cost
动态规划·leetcode hard·trie树·leetcode 3213·leetcode周赛405
Espresso Macchiato3 个月前
Leetcode 3203. Find Minimum Diameter After Merging Two Trees
leetcode hard·图算法·拓扑图·leetcode 3203·leetcode 周赛404
wang09073 个月前
数据结构之前缀树
数据结构·前缀树·trie树
Espresso Macchiato3 个月前
Leetcode 3193. Count the Number of Inversions
leetcode·动态规划·leetcode hard·leetcode 3193·leetcode双周赛133
Espresso Macchiato4 个月前
Leetcode 3187. Peaks in Array
leetcode hard·leetcode周赛402·leetcode 3187·segment tree·分段树
闻缺陷则喜何志丹4 个月前
【字典树(前缀树) 哈希映射 后序序列化】1948. 删除系统中的重复文件夹
linux·c++·算法·哈希算法·字典树·哈希映射·后序序列化
Espresso Macchiato5 个月前
Leetcode 3145. Find Products of Elements of Big Array
二进制·二分法·leetcode hard·leetcode双周赛130·leetcode 3145