原题链接在这里: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.
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
.
题解:
查找词用到Trie树.
addword和Implement Trie (Prefix Tree)相同. search时利用dfs, 终止条件有两种.
一种是string 还没扫完, 已经走到了null节点, return false.
另一种扫完了string, 要看是否到了Trie树的叶子节点.
dfs过程分两种情况,一种情况是当前char 是'.', 此时应该跳过这个char, 同时对剩余string和tn.nexts 的所有储存的节点继续迭代,若有一个正好走到叶子节点, 就返回ture; 若没有一个正好走到叶子节点,就return false.
另一种情况是当前char不是'.', 就继续用root.nexts[c-'a'] 和 word, i+1 index做dfs.
Time Complexity: addWord, O(n). search, O(26^n), n是string 长度. worst case每一个路径都要扫.
Space: (m*n). m is number of words added.
AC Java:
1 class WordDictionary { 2 TrieNode root; 3 4 /** Initialize your data structure here. */ 5 public WordDictionary() { 6 root = new TrieNode(); 7 } 8 9 /** Adds a word into the data structure. */ 10 public void addWord(String word) { 11 TrieNode p = root; 12 for(char c : word.toCharArray()){ 13 if(p.nexts[c - 'a'] == null){ 14 p.nexts[c - 'a'] = new TrieNode(); 15 } 16 17 p = p.nexts[c - 'a']; 18 } 19 20 p.val = word; 21 } 22 23 /** Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter. */ 24 public boolean search(String word) { 25 if(word == null || word.length() == 0){ 26 return false; 27 } 28 29 return searchWord(word, 0, root); 30 } 31 32 private boolean searchWord(String word, int index, TrieNode p){ 33 if(p == null){ 34 return false; 35 } 36 37 if(index == word.length()){ 38 return p.val != null; 39 } 40 41 if(word.charAt(index) == '.'){ 42 for(TrieNode next : p.nexts){ 43 if(searchWord(word, index + 1, next)){ 44 return true; 45 } 46 } 47 48 }else{ 49 return searchWord(word, index + 1, p.nexts[word.charAt(index) - 'a']); 50 } 51 52 return false; 53 } 54 } 55 56 class TrieNode{ 57 String val; 58 TrieNode [] nexts; 59 60 public TrieNode(){ 61 nexts = new TrieNode[26]; 62 } 63 } 64 65 /** 66 * Your WordDictionary object will be instantiated and called as such: 67 * WordDictionary obj = new WordDictionary(); 68 * obj.addWord(word); 69 * boolean param_2 = obj.search(word); 70 */