211. Add and Search Word - Data structure design
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.children.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 26 char c = word.charAt(index); 27 if (c == '.') { 28 for (TrieNode child : current.children.values()) { 29 if (helper(child, word, index + 1)) return true; 30 } 31 } else { 32 return helper(current.getChildNode(word.charAt(index)), word, index + 1); 33 } 34 return false; 35 } 36 } 37 38 class TrieNode { 39 char ch; 40 boolean isEnd; 41 Map<Character, TrieNode> children; 42 43 public TrieNode(char ch) { 44 this.ch = ch; 45 children = new HashMap<>(); 46 } 47 48 public TrieNode getChildNode(char ch) { 49 return children.get(ch); 50 } 51 }