211 Add and Search Word - Data structure design

1. Question

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 lettersa-zor.. A.means it can represent any one letter.

For 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 lettersa-z.

2. Implementation

(1) Trie + Backtracking

3. Time & Space Complexity

时间复杂度: insert: O(w * L), search: O(26^m), w为放在trie的word的个数,L为word的平均长度,m为查询的word的长度

空间复杂度: O(w * L)

Last updated

Was this helpful?