您的位置:首页 > 其它

Add and Search Word - Data structure design

2015-09-29 20:26 204 查看
题意:

字典树的插入和查找

分析:

easy

参考代码:
http://www.programcreek.com/2014/05/leetcode-add-and-search-word-data-structure-design-java/
class TrieNode{
char c;
HashMap<Character, TrieNode> children = new HashMap<Character, TrieNode>();
boolean isLeaf;

public TrieNode() {}

public TrieNode(char c){
this.c = c;
}
}
public class WordDictionary {
private 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;

for(int i=0; i<word.length(); i++){
char c = word.charAt(i);

TrieNode t = null;
if(children.containsKey(c)){
t = children.get(c);
}else{
t = new TrieNode(c);
children.put(c,t);
}

children = t.children;

if(i == word.length()-1){
t.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 dfsSearch(root.children, word, 0);

}

public boolean dfsSearch(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 dfsSearch(children.get(c).children, word, start+1);
}else if(c == '.'){
boolean result = false;
for(Map.Entry<Character, TrieNode> child: children.entrySet()){
if(start == word.length()-1 && child.getValue().isLeaf){
return true;
}

//if any path is true, set result to be true;
if(dfsSearch(child.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");
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: