211. 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.
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 letters a-z.
Thoughts
查字典里是否出现给定的一系列单词,单词中的'.'可代表任意字符。和普通trie的区别在于有"."能代表任意字符,利用DFS遍历所有的子树直到找到。DFS时当前结点是pos指定的字符的父节点,因此当循环完单词后节点就是最后一个字符所代表的节点,检查它是否是单词结束。
Code
Analysis
Errors: 1. 没有在backtracking循环后写return false.
search的时间复杂度T(l) = 26 T(l - 1) = 26 26 * T(l - 2)...因此是O(26 ^ l). 插入还是O(l).
Last updated
Was this helpful?