Design a data structure that supports the following two operations: addWord(word)
andsearch(word)
search(word)
can search a literal word or a regular expression string containing only lettersa-z
or .
.
A .
means it can represent any one letter.
Notice
You may assume that all words are consist of lowercase letters a-z.
Example
addWord("bad") addWord("dad") addWord("mad") search("pad") // return false search("bad") // return true search(".ad") // return true search("b..") // return true
使用Trie
1 public class WordDictionary { 2 private TrieNode root = new TrieNode(' '); 3 public void addWord(String word) { 4 TrieNode current = root; 5 for (int i = 0; i < word.length(); i++) { 6 char ch = word.charAt(i); 7 TrieNode node = current.getChildNode(ch); 8 if (node == null) { 9 current.map.put(ch, new TrieNode(ch)); 10 node = current.getChildNode(ch); 11 } 12 current = node; 13 } 14 current.isEnd = true; 15 } 16 17 // Returns if the word is in the trie. 18 public boolean search(String word) { 19 return helper(root, word, 0); 20 } 21 22 public boolean helper(TrieNode current, String word, int index) { 23 if (current == null) return false; 24 if (index == word.length()) return current.isEnd; 25 char c = word.charAt(index); 26 if (c == '.') { 27 for (TrieNode child : current.map.values()) { 28 if (helper(child, word, index + 1)) return true; 29 } 30 } else { 31 return helper(current.getChildNode(word.charAt(index)), word, index + 1); 32 } 33 return false; 34 } 35 } 36 37 class TrieNode { 38 char ch; 39 boolean isEnd; 40 Map<Character, TrieNode> map; 41 42 public TrieNode(char ch) { 43 this.ch = ch; 44 map = new HashMap<>(); 45 } 46 47 public TrieNode getChildNode(char ch) { 48 return map.get(ch); 49 } 50 }