Design a data structure that supports the following two operations: addWord(word)
and 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.
addWord("bad")
addWord("dad")
addWord("mad")
search("pad") // return false
search("bad") // return true
search(".ad") // return true
search("b..") // return true
这题细说太麻烦,看看trie/prefix tree就解决了
public class WordDictionary { class TrieNode{ char c; HashMap<Character, TrieNode> children; boolean isLeaf; public TrieNode(){ this.children = new HashMap<Character, TrieNode>(); this.isLeaf = false; } public TrieNode(char c){ this.c = c; this.children = new HashMap<Character, TrieNode>(); this.isLeaf = false; } } TrieNode root; public WordDictionary(){ this.root = new TrieNode(); } // Adds a word into the data structure. public void addWord(String word) { // Write your code here if(word == null || word.length() == 0) return; TrieNode temp = root; for(int i = 0; i < word.length(); i++){ char c = word.charAt(i); if(temp.children.containsKey(c)){ temp = temp.children.get(c); } else{ temp.children.put(c, new TrieNode(c)); temp = temp.children.get(c); } if(i == word.length() - 1) temp.isLeaf = true; } return; } // Returns if the word is in the data structure. A word could // contain the dot character '.' to represent any one letter. public boolean search(String word) { // Write your code here if(word == null || word.length() == 0) return true; char[] array = word.toCharArray(); return search(root, array, 0); } public boolean search(TrieNode root, char[] array, int start){ if(start == array.length && root.isLeaf) return true; else if(start == array.length) return false; if(array[start] != '.'){ if(root.children.containsKey(array[start])) return search(root.children.get(array[start]), array, start + 1); else return false; } else{ for(Map.Entry<Character, TrieNode> entry: root.children.entrySet()){ if(search(root.children.get(entry.getKey()), array, start + 1)) return true; } return false; } } } // Your WordDictionary object will be instantiated and called as such: // WordDictionary wordDictionary = new WordDictionary(); // wordDictionary.addWord("word"); // wordDictionary.search("pattern");