题目211. 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.
public class WordDictionary {
static class TrieNode{
boolean isLeaf;
Map<Character,TrieNode> content;
TrieNode(){
content = new HashMap<Character,TrieNode>();
}
}
private TrieNode root;
public WordDictionary() {
root = new TrieNode();
}
// Adds a word into the data structure.
public void addWord(String word) {
if(word == null || word.length() == 0){
return;
}
TrieNode node = root;
TrieNode tempNode = null;;
for(int i=0, len=word.length(); i<len; i++){
Character c = word.charAt(i);
tempNode = node.content.get(c);
if(tempNode == null){
tempNode = new TrieNode();
node.content.put(c,tempNode);
}
node = tempNode;
}
node.isLeaf = true;
}
// 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) {
return search(0,word,root);
}
private boolean search(int idx, String word, TrieNode root){
if(word == null || word.length() == 0){
return false;
}
TrieNode node = root;
TrieNode tempNode = null;
for(int i=idx, len=word.length(); i<len; i++){
Character c = word.charAt(i);
if('.' == c){
Map<Character,TrieNode> map = node.content;
Set<Character> keys = map.keySet();
boolean result = false;
for(Character ch : keys){
TrieNode trieNode = map.get(ch);
if((i == (len-1)) && trieNode.isLeaf){
return true;
}
if(i >= len){
return false;
}
result = result || search(i+1,word,map.get(ch));
}
return result;
}else{
tempNode = node.content.get(c);
if(tempNode == null){
return false;
}
node = tempNode;
}
}
return node.isLeaf;
}
}
// Your WordDictionary object will be instantiated and called as such:
// WordDictionary wordDictionary = new WordDictionary();
// wordDictionary.addWord("word");
// wordDictionary.search("pattern");