211. Add and Search Word - Data structure design

Question 211

https://leetcode.com/problems/add-and-search-word-data-structure-design

Design a data structure that supports the following two operations:

void addWord(word)
bool search(word)

search(word) can search a literal word or a regular expression string containing only letters a-z or .. A .means it can represent any one letter.

Example:

addWord("bad")
addWord("dad")
addWord("mad")
search("pad") -> false
search("bad") -> true
search(".ad") -> true
search("b..") -> true

Note: You may assume that all words are consist of lowercase letters a-z.

Answer

v1.use defaultdict (98.83%)

  1. 建立一個 collections class 中的 defaultdict() ,命名為 word_store

  2. [addWord] --> 依據字串長度來分 list 存: [ ( 2, ["ab", "dv"] ), ( 1, ["a","b","c"] ), ( 6, [ "asdfgh"] ) ]

  3. [search] -->

    a) 如果該 search 字串沒有 “.” ,直接找 word_store 中該長度的字串有沒有符合的 b) 如果有 “.”,一個字母一個字母去比對該長度 list 中的字詞

Last updated