745. Prefix and Suffix Search
題目網址:https://leetcode.cn/problems/prefix-and-suffix-search/
題意:設計一個可以透過 prefix 和 suffix 來搜尋單字的特殊字典。
請實現
WordFilter
class:
WordFilter(string[] words)
:使用word
來初始化WordFilter
f(string pref, string suff)
:返回字典中具有前綴prefix
和後綴suffix
單字的 index。若不只一個 index 滿足要求, 則返回最大的 index。若不存在這樣的單字, 則返回1
。其中,
words[i]
、pref
、suff
僅由小寫字母所組成。
Solution 1:
想法:利用 hash table 去儲存每個單字所有可能的
prefix_suffix
組合, 並對應到該單字的 index。若有單字有相同的prefix_suffix
組合, 則後面的單字會覆蓋掉前面的單字之 index
紀錄該單字的
prefixes
、suffixes
長度為n + 1
, 其中n
為該單字的長度, 因為要加上 empty stringe.g.
word = ["abc"]
, 可得到:
prefixes = ["", "a", "ab", "abc"]
suffixes = ["", "c", "bc", "abc"]
- 所有的
prefix_suffix
組合總共有(3+1) x (3+1) = 16
種建立
prefixes
、suffixes
需 $O(n^2)$ time, 因為 stringc = a + b
, 需 $O(a.size() + b.size())$
➔ 建立prefix = suffix = 1 + 2 + ... + n
= $O(n^2)$
class WordFilter { |
- time:
WordFilter()
:$O(\sum\limits_{i = 0}^{n-1}{w_i^3})$, 其中 $w_i$ 為單字長度, 總共有 $n$ 個單字- 每個單字建立
prefixes
,suffixes
需 $O(w_i^2)$, 總共需花 $O(\sum\limits_{i = 0}^{n-1}{w_i^2})$ - 每個單字總共有 $O(w_i^2)$ 種
prefix_suffix
組合, 而每一種組合需花 $O(w_i)$ 建立對應的key
, 也就是prefix + "_" + suffix
。因此每個單字需花 $O(w_i^3)$ 建立所有的prefix_suffix
組合, 總共需花 $O(\sum\limits_{i = 0}^{n-1}{w_i^3})$
- 每個單字建立
f()
:$O(p + s)$, 建立 key 的時間複雜度, 其中 $p$ 為pref
長度, $s$ 為suff
長度
- space:$O(\sum\limits_{i = 0}^{n-1}{w_i^3})$ ➔
filter
, 每個單字有 $O(w_i^2)$ 種prefix_suffix
組合, 而每一種又有長度為 $O(w_i)$ 的key
, 因此每個單字需 $O(w_i^3)$, 總共需 $O(\sum\limits_{i = 0}^{n-1}{w_i^3})$
Solution 2:
想法:利用 Trie, 本題最大的困難點在於不知如何搜尋以
suffix
結尾的單字, 對於每個單字 word, 我們把所有可能的suffixes_word
組合 insert 到 trie 中(因為 word 本身滿足 prefix 順序)。最後, 用suff_pref
來做搜尋e.g.
word = ["apple"]
可產生以下suffixes_word
組合:["_apple", "e_apple", "le_apple", "ple_apple", "pple_apple", "apple_apple"]
另外, 使用
{
作為分隔符, 用來隔開prefix
和suffix
, 因為{
在 ASCII 中恰好是z
的下一個, 這樣就不用額外寫判斷式
class TrieNode{ |
- time:
WordFilter()
:$O(\sum\limits_{i = 0}^{n-1}{w_i^2})$, 其中 $w_i$ 為單字長度, 總共有 $n$ 個單字- 每個單字建立所有的
suffixes_word
組合需 $O({w_i}^2)$, 總共需 $O(\sum\limits_{i = 0}^{n-1}{w_i^2})$
- 每個單字建立所有的
f()
:$O(p + s)$, 其中 $p$ 為pref
的長度, $s$ 為suff
的長度- 建立 string
suff_pref
- 在
trie
中搜尋suff_pref
- 建立 string
- space:$O(\sum\limits_{i = 0}^{n-1}{w_i}^2)$ ➔
trie
, 每個單字有 $O(w_i)$ 種suffixes_word
組合, 而每一種長度為 $O(w_i)$。因此 在 worse case 中(沒有任何共用 prefix 的情況下)每個單字建立所有的suffixes_word
組合需 $O(w_i^2)$, 總共需 $O(\sum\limits_{i = 0}^{n-1}{w_i^2})$