您的位置:首页 > 其它

Add and Search Word - Data structure design

2015-08-17 21:05 375 查看
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

与上一题相似,同样用到Trie Node,不同之处是search时,.号需要遍历DFS匹配。

public class WordDictionary {
TrieNode root;
public WordDictionary(){
root=new TrieNode();
}
// Adds a word into the data structure.
public void addWord(String word) {
HashMap<Character,TrieNode> children=root.children;
TrieNode tmp;
for(int i=0;i<word.length();i++){
char c=word.charAt(i);
if(children.containsKey(c)){
tmp=children.get(c);
}else{
tmp=new TrieNode(c);
children.put(c, tmp);
}
children=tmp.children;
if(i==word.length()-1)
tmp.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) {
HashMap<Character,TrieNode> children=root.children;
return bfs(children,word,0);
}
private boolean bfs(HashMap<Character,TrieNode> children,String word,int start){
if(start==word.length()){
if(children.size()==0)
return true;
else
return false;
}
char c=word.charAt(start);
if(children.containsKey(c)){
if(start==word.length()-1&&children.get(c).isLeaf)
return true;
return bfs(children.get(c).children,word,start+1);
}else if(c=='.'){
boolean result=false;
for(Map.Entry<Character, TrieNode> t:children.entrySet()){
if(start==word.length()-1&&t.getValue().isLeaf)
return true;
if(bfs(t.getValue().children,word,start+1))
result=true;
}
return result;
}else
return false;
}
}

// Your WordDictionary object will be instantiated and called as such:
// WordDictionary wordDictionary = new WordDictionary();
// wordDictionary.addWord("word");
// wordDictionary.search("pattern");
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: