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 lettersa-z .
<Solution>You may assume that all words are consist of lowercase letters
這題可以看成是 208. Implement Trie (Prefix Tree) 的衍生題
主要想法差不多,唯一比較不一樣的地方是,這次搜尋的可以用萬用字元
想法如下
- 如果沒遇到萬用字元,那麼就是正常歷遍 Prefix Tree 來找
- 如果遇到萬用字元,那麼歷遍當下 node 所有可連接的節點,並配合 dfs 的方式來找
code 如下
Java
沒有留言:
張貼留言