LC Trie

Catalog:
LC 745 [Prefix and Suffix Search]
LC 676 [Implement Magic Dictionary]
LC 208 Implement Trie (Prefix Tree)
LC 211 Add and Search Word -- Data Structure Design
[Uber] 642 Design Search Autocomplete System

[Uber]LC 745 Prefix and Suffix Search
Method 1: build all possible prefix and suffix combination in a dictionary and words with higher weight will overwrite the previous record. This is for quick look up!

class WordFilter(object):

    def __init__(self, words):
        self.d = {}
        for index, word in enumerate(words):
            prefix = ''
            for char in [''] + list(word):
                prefix += char
                suffix = ''
                for char in [''] + list(word[::-1]):
                    suffix += char
                    self.d[prefix + '.' + suffix[::-1]] = index

    def f(self, prefix, suffix):
        return self.d.get(prefix + '.' + suffix, -1)

Store pre and suffix, look up is slower but it is quicker to build

class WordFilter(object):

    def __init__(self, words):
        self.prefix=defaultdict(set)
        self.suffix=defaultdict(set)
        self.ind={}

        for i,w in enumerate(words):
            self.ind[w]=i
            n=len(w)
            for i in range(n+1):
                self.prefix[w[:i]].add(w)
                self.suffix[w[n-i:]].add(w)

    def f(self, prefix, suffix):
        pool=self.prefix[prefix]&self.suffix[suffix]
        return max(self.ind[w] for w in pool) if pool else -1  

Not using Trie Structure could lead a very big space complexity when N is very big. Trie would be recommended to save space and get O(L) find time complexity!

The way we will look up the Trie is using combination of prefix and suffix, for example, pre + '#' + suf. That's what we are going to insert when we get a word

TrieNode should have a field called weight, and a method to insert new pair.

LC 676 Implement Magic Dictionary

Trie (we pronounce "try") or prefix tree is a tree data structure, which is used for retrieval of a key in a dataset of strings. There are various applications of this very efficient data structure such as : Autocomplete, Spell checker, IP routing (Longest prefix matching), T9 predictive text, Solving word games.

There are several other data structures, like balanced trees and hash tables, which give us the possibility to search for a word in a dataset of strings. Then why do we need trie? Although hash table has O(1)O(1)O(1) time complexity for looking for a key, it is not efficient in the following operations :
?Finding all keys with a common prefix.
?Enumerating a dataset of strings in lexicographical order.

Trie could use less space compared to Hash Table when storing many keys with the same prefix. In this case using trie has only O(m) time complexity, where m is the key length. Searching for a key in a balanced tree costs O(mlogn) time complexity.

LC 208 Implement Trie (Prefix Tree)
Implement a trie with insert, search, and startsWith methods.

class TrieNode(object):
    def __init__(self):
        self.is_word = False
        self.children = collections.defaultdict(TrieNode)

class Trie(object):
    def __init__(self):
        self.root = TrieNode()

    def insert(self, word):
        node = self.root
        for c in word:
            node = node.children[c]
        node.is_word = True

    def search(self, word, search_word=True):
        node = self.root
        for c in word:
            if c not in node.children:
                return False
            node = node.children[c]
        return node.is_word if search_word else True

    def startsWith(self, prefix):
        return self.search(prefix, False)

LC 211 Add and Search Word -- Data Structure Design
Implement a class called WordDictionary with add and search methods. Search(word) can search a literal word or a regular expression string containing only letters a-z or . (any one letter).
Hash table and bucket by len(word) -- collision if the word length are the same or quite gather together. So if we only need to add and search, and we do not need frequency counting, it is definitely better to use Trie.

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子姿搜,更是在濱河造成了極大的恐慌婉陷,老刑警劉巖纱皆,帶你破解...
    沈念sama閱讀 216,544評(píng)論 6 501
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件州袒,死亡現(xiàn)場(chǎng)離奇詭異震束,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī)馏鹤,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,430評(píng)論 3 392
  • 文/潘曉璐 我一進(jìn)店門(mén),熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)娇哆,“玉大人湃累,你說(shuō)我怎么就攤上這事“郑” “怎么了治力?”我有些...
    開(kāi)封第一講書(shū)人閱讀 162,764評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)勃黍。 經(jīng)常有香客問(wèn)我宵统,道長(zhǎng),這世上最難降的妖魔是什么覆获? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,193評(píng)論 1 292
  • 正文 為了忘掉前任马澈,我火速辦了婚禮,結(jié)果婚禮上锻梳,老公的妹妹穿的比我還像新娘箭券。我一直安慰自己,他們只是感情好疑枯,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,216評(píng)論 6 388
  • 文/花漫 我一把揭開(kāi)白布辩块。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪废亭。 梳的紋絲不亂的頭發(fā)上国章,一...
    開(kāi)封第一講書(shū)人閱讀 51,182評(píng)論 1 299
  • 那天,我揣著相機(jī)與錄音豆村,去河邊找鬼液兽。 笑死,一個(gè)胖子當(dāng)著我的面吹牛掌动,可吹牛的內(nèi)容都是我干的四啰。 我是一名探鬼主播,決...
    沈念sama閱讀 40,063評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼粗恢,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼柑晒!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起眷射,我...
    開(kāi)封第一講書(shū)人閱讀 38,917評(píng)論 0 274
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤匙赞,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后妖碉,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體涌庭,經(jīng)...
    沈念sama閱讀 45,329評(píng)論 1 310
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,543評(píng)論 2 332
  • 正文 我和宋清朗相戀三年欧宜,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了坐榆。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 39,722評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡鱼鸠,死狀恐怖猛拴,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情蚀狰,我是刑警寧澤愉昆,帶...
    沈念sama閱讀 35,425評(píng)論 5 343
  • 正文 年R本政府宣布,位于F島的核電站麻蹋,受9級(jí)特大地震影響跛溉,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜扮授,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,019評(píng)論 3 326
  • 文/蒙蒙 一芳室、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧刹勃,春花似錦堪侯、人聲如沸。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 31,671評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)芽死。三九已至,卻和暖如春次洼,著一層夾襖步出監(jiān)牢的瞬間关贵,已是汗流浹背。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 32,825評(píng)論 1 269
  • 我被黑心中介騙來(lái)泰國(guó)打工卖毁, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留揖曾,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 47,729評(píng)論 2 368
  • 正文 我出身青樓亥啦,卻偏偏與公主長(zhǎng)得像炭剪,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子禁悠,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,614評(píng)論 2 353

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