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 3791. Number of Balanced Integers in a Range
leetcode hard·leetcode周赛482·leetcode 3791
Espresso Macchiato2 天前
Leetcode 3782. Last Remaining Integer After Alternating Deletion Operations
迭代·leetcode hard·leetcode双周赛172·leetcode 3782
Espresso Macchiato2 天前
Leetcode 3768. Minimum Inversion Count in Subarrays of Fixed Length
滑动窗口·leetcode hard·leetcode双周赛171·leetcode 3768
Espresso Macchiato3 天前
Leetcode 3785. Minimum Swaps to Avoid Forbidden Values
leetcode hard·leetcode周赛481·leetcode 3785
Espresso Macchiato3 天前
Leetcode 3786. Total Sum of Interaction Cost in Tree Groups
leetcode hard·leetcode 3786·leetcode周赛481
scx2013100411 天前
20251214 字典树总结
算法·字典树
Dream it possible!17 天前
LeetCode 面试经典 150_字典树_添加与搜索单词 - 数据结构设计(96_211_C++_中等)
c++·leetcode·面试·字典树
louisdlee.18 天前
保姆级教学——字典树
字典树
_OP_CHEN1 个月前
【算法基础篇】(二十六)数据结构封神!Trie 树从入门到爆杀算法题:拼音输入法、单词统计都靠它
数据结构·c++·算法·蓝桥杯·trie树·算法竞赛·acm/icpc
adam_life1 个月前
【P8306 【模板】字典树】
数据结构·算法·字典树·trie·哈希表··结构体