LeetCode #745 Prefix and Suffix Search 前綴和后綴搜索

745 Prefix and Suffix Search 前綴和后綴搜索

Description:
Design a special dictionary with some words that searchs the words in it by a prefix and a suffix.

Implement the WordFilter class:

WordFilter(string[] words) Initializes the object with the words in the dictionary.
f(string prefix, string suffix) Returns the index of the word in the dictionary, which has the prefix prefix and the suffix suffix. If there is more than one valid index, return the largest of them. If there is no such word in the dictionary, return -1.

Example:

Example 1:

Input
["WordFilter", "f"]
[[["apple"]], ["a", "e"]]
Output
[null, 0]

Explanation

WordFilter wordFilter = new WordFilter(["apple"]);
wordFilter.f("a", "e"); // return 0, because the word at index 0 has prefix = "a" and suffix = 'e".

Constraints:

1 <= words.length <= 15000
1 <= words[i].length <= 10
1 <= prefix.length, suffix.length <= 10
words[i], prefix and suffix consist of lower-case English letters only.
At most 15000 calls will be made to the function f.

題目描述:
設(shè)計一個包含一些單詞的特殊詞典哄辣,并能夠通過前綴和后綴來檢索單詞请梢。

實(shí)現(xiàn) WordFilter 類:

WordFilter(string[] words) 使用詞典中的單詞 words 初始化對象。
f(string prefix, string suffix) 返回詞典中具有前綴 prefix 和后綴suffix 的單詞的下標(biāo)力穗。如果存在不止一個滿足要求的下標(biāo)溢陪,返回其中 最大的下標(biāo) 。如果不存在這樣的單詞睛廊,返回 -1 。

示例 :

輸入:
["WordFilter", "f"]
[[["apple"]], ["a", "e"]]
輸出:
[null, 0]

解釋:

WordFilter wordFilter = new WordFilter(["apple"]);
wordFilter.f("a", "e"); // 返回 0 杉编,因?yàn)橄聵?biāo)為 0 的單詞的 prefix = "a" 且 suffix = 'e" 超全。

提示:

1 <= words.length <= 15000
1 <= words[i].length <= 10
1 <= prefix.length, suffix.length <= 10
words[i]、prefix 和 suffix 僅由小寫英文字母組成
最多對函數(shù) f 進(jìn)行 15000 次調(diào)用

思路:

前綴樹
將前綴和后綴用分隔符, 如 "#" 連在一起
即可用普通的前綴樹求解
時間復(fù)雜度為 O(mn ^ 2), 空間復(fù)雜度為 O(mn ^ 2), m 為 words 的長度, n 為 word 的長度

代碼:
C++:

class Trie
{
private:
    Trie *children[27]{ nullptr };
    int val = 0;
public:
    
    void insert(string &word, int start, int cur_val)
    {
        Trie *p = this;
        for (int i = start, s = word.size(); i < s; i++)
        {
            int cur = word[i] == '#' ? 26 : word[i] - 'a';
            if (!p -> children[cur]) p -> children[cur] = new Trie;
            p = p -> children[cur];
            p -> val = max(p -> val, cur_val);
        }
    }
    
    int search(string &word)
    {
        Trie *p = this;
        for (int i = 0, s = word.size(); i < s; i++)
        {
            int cur = word[i] == '#' ? 26 : word[i] - 'a';
            if (!p -> children[cur]) return -1;
            else p = p -> children[cur];
        }
        return p -> val;
    }
};
class WordFilter 
{
private:
    Trie root;
public:
    WordFilter(vector<string>& words) 
    {
        string cur;
        for (int i = 0, s = words.size(); i < s; i++)
        {
            cur = words[i] + "#" + words[i];
            for (int j = 0, t = words[i].size(); j <= t; j++) root.insert(cur, j, i);
        }
    }
    
    int f(string prefix, string suffix) 
    {
        string target = suffix + "#" + prefix;
        return root.search(target);
    }
    
};

/**
 * Your WordFilter object will be instantiated and called as such:
 * WordFilter* obj = new WordFilter(words);
 * int param_1 = obj->f(prefix,suffix);
 */

Java:

class WordFilter {
    private Map<String, Integer> map = new HashMap<>();
    public WordFilter(String[] words) {
        for (int i = 0; i < words.length; i++) for (int j = 1; j <= words[i].length(); j++) for (int k = 1; k <= words[i].length(); k++) map.put(words[i].substring(0, j) + "#" + words[i].substring(words[i].length() - k, words[i].length()), i);
    }
        
    public int f(String prefix, String suffix) {
        return map.getOrDefault(prefix + "#" + suffix, -1);
    }
}

/**
 * Your WordFilter object will be instantiated and called as such:
 * WordFilter obj = new WordFilter(words);
 * int param_1 = obj.f(prefix,suffix);
 */

Python:

class WordFilter:

    def __init__(self, words: List[str]):
        self.d = {}
        for i, w in enumerate(words):
            for j in range(0, len(w) + 1):
                p = w[:j]
                for k in range(0, len(w) + 1):
                    q = w[k:]
                    self.d[(p, q)] = i


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



# Your WordFilter object will be instantiated and called as such:
# obj = WordFilter(words)
# param_1 = obj.f(prefix,suffix)
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末邓馒,一起剝皮案震驚了整個濱河市嘶朱,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌光酣,老刑警劉巖疏遏,帶你破解...
    沈念sama閱讀 218,386評論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異救军,居然都是意外死亡财异,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,142評論 3 394
  • 文/潘曉璐 我一進(jìn)店門唱遭,熙熙樓的掌柜王于貴愁眉苦臉地迎上來戳寸,“玉大人,你說我怎么就攤上這事拷泽∫呷担” “怎么了?”我有些...
    開封第一講書人閱讀 164,704評論 0 353
  • 文/不壞的土叔 我叫張陵司致,是天一觀的道長拆吆。 經(jīng)常有香客問我,道長脂矫,這世上最難降的妖魔是什么枣耀? 我笑而不...
    開封第一講書人閱讀 58,702評論 1 294
  • 正文 為了忘掉前任,我火速辦了婚禮庭再,結(jié)果婚禮上奕枢,老公的妹妹穿的比我還像新娘娄昆。我一直安慰自己,他們只是感情好缝彬,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,716評論 6 392
  • 文/花漫 我一把揭開白布萌焰。 她就那樣靜靜地躺著,像睡著了一般谷浅。 火紅的嫁衣襯著肌膚如雪扒俯。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,573評論 1 305
  • 那天一疯,我揣著相機(jī)與錄音撼玄,去河邊找鬼。 笑死墩邀,一個胖子當(dāng)著我的面吹牛掌猛,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播眉睹,決...
    沈念sama閱讀 40,314評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼荔茬,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了竹海?” 一聲冷哼從身側(cè)響起慕蔚,我...
    開封第一講書人閱讀 39,230評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎斋配,沒想到半個月后孔飒,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,680評論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡艰争,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,873評論 3 336
  • 正文 我和宋清朗相戀三年坏瞄,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片甩卓。...
    茶點(diǎn)故事閱讀 39,991評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡惦积,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出猛频,到底是詐尸還是另有隱情狮崩,我是刑警寧澤,帶...
    沈念sama閱讀 35,706評論 5 346
  • 正文 年R本政府宣布鹿寻,位于F島的核電站睦柴,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏毡熏。R本人自食惡果不足惜坦敌,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,329評論 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧狱窘,春花似錦杜顺、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,910評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至搭儒,卻和暖如春穷当,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背淹禾。 一陣腳步聲響...
    開封第一講書人閱讀 33,038評論 1 270
  • 我被黑心中介騙來泰國打工馁菜, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人铃岔。 一個月前我還...
    沈念sama閱讀 48,158評論 3 370
  • 正文 我出身青樓汪疮,卻偏偏與公主長得像,于是被迫代替她去往敵國和親毁习。 傳聞我的和親對象是個殘疾皇子智嚷,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,941評論 2 355

推薦閱讀更多精彩內(nèi)容