LeetCode 题解工作台

前缀和后缀搜索

设计一个包含一些单词的特殊词典,并能够通过前缀和后缀来检索单词。 实现 WordFilter 类: WordFilter(string[] words) 使用词典中的单词 words 初始化对象。 f(string pref, string suff) 返回词典中具有前缀 pref 和后缀 suff…

category

5

题型

code_blocks

4

代码语言

hub

3

相关题

当前训练重点

困难 · 数组·哈希·扫描

bolt

答案摘要

遍历 的每个单词 ,将 的所有前缀、后缀对存放到哈希表中。 class WordFilter:

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数组·哈希·扫描 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

设计一个包含一些单词的特殊词典,并能够通过前缀和后缀来检索单词。

实现 WordFilter 类:

  • WordFilter(string[] words) 使用词典中的单词 words 初始化对象。
  • f(string pref, string suff) 返回词典中具有前缀 pref 和后缀 suff 的单词的下标。如果存在不止一个满足要求的下标,返回其中 最大的下标 。如果不存在这样的单词,返回 -1

 

示例:

输入
["WordFilter", "f"]
[[["apple"]], ["a", "e"]]
输出
[null, 0]
解释
WordFilter wordFilter = new WordFilter(["apple"]);
wordFilter.f("a", "e"); // 返回 0 ,因为下标为 0 的单词:前缀 prefix = "a" 且 后缀 suffix = "e" 。
 

提示:

  • 1 <= words.length <= 104
  • 1 <= words[i].length <= 7
  • 1 <= pref.length, suff.length <= 7
  • words[i]prefsuff 仅由小写英文字母组成
  • 最多对函数 f 执行 104 次调用
lightbulb

解题思路

方法一:暴力哈希

遍历 wordswords 的每个单词 ww,将 ww 的所有前缀、后缀对存放到哈希表中。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class WordFilter:
    def __init__(self, words: List[str]):
        self.d = {}
        for k, w in enumerate(words):
            n = len(w)
            for i in range(n + 1):
                a = w[:i]
                for j in range(n + 1):
                    b = w[j:]
                    self.d[(a, b)] = k

    def f(self, pref: str, suff: str) -> int:
        return self.d.get((pref, suff), -1)


# Your WordFilter object will be instantiated and called as such:
# obj = WordFilter(words)
# param_1 = obj.f(pref,suff)
speed

复杂度分析

指标
时间O(NK^2 + QK)
空间O(NK^2)
psychology

面试官常问的追问

外企场景
  • question_mark

    The candidate demonstrates understanding of Trie structures and hashing for prefix-suffix matching.

  • question_mark

    They should consider how to optimize space usage while maintaining efficiency in multiple queries.

  • question_mark

    Look for attention to detail when managing combinations of prefixes and suffixes in the Trie.

warning

常见陷阱

外企场景
  • error

    Overcomplicating the design by not leveraging the Trie structure effectively.

  • error

    Failing to optimize for multiple queries by not using hash-based lookups.

  • error

    Not handling the space complexity efficiently, leading to excessive memory usage.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Consider modifying the problem to handle a fixed-size dictionary and optimize for multiple queries using pre-processing techniques.

  • arrow_right_alt

    A variant could involve supporting more complex patterns beyond simple prefix and suffix matching, like substrings.

  • arrow_right_alt

    Handling words with overlapping prefixes and suffixes might require additional data structures or optimizations.

help

常见问题

外企场景

前缀和后缀搜索题解:数组·哈希·扫描 | LeetCode #745 困难