您的位置:首页 > 其它

211. Add and Search Word - Data structure design

2016-07-22 23:45 281 查看
就是trie

public class WordDictionary {
public class TrieNode {
public TrieNode[] child;
public char curChar;
public boolean isLeaf;

public TrieNode() {
child = new TrieNode[26];
isLeaf = false;
}
}

TrieNode root;

public WordDictionary() {
root = new TrieNode();
}

// Adds a word into the data structure.
public void addWord(String word) {
if(word.length() == 0) {
return;
}
TrieNode curNode = root;
for(int i = 0; i < word.length(); i++) {
char cur = word.charAt(i);
int index = cur - 'a';
if(curNode.child[index] ==  null) {
curNode.child[index] = new TrieNode();
curNode.child[index].curChar = cur;
}
curNode = curNode.child[index];
}
curNode.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) {
if(word.length() == 0) {
return true;
}
return searchHelper(word, root);
}

private boolean searchHelper(String word, TrieNode curNode) {
if(word.length() == 0) {
return curNode.isLeaf;
}
char cur = word.charAt(0);
String sub = word.substring(1);
if(cur != '.') {
int index = cur - 'a';
if(curNode.child[index] == null) {
return false;
}
if(curNode.child[index].curChar != cur) {
return false;
}
return searchHelper(sub, curNode.child[index]);
} else {
for(int i = 0; i < 26; i++) {
if(curNode.child[i] != null && searchHelper(sub, curNode.child[i])) {
return true;
}
}
}
return false;
}
}


68行那里要return false因为在62行处,可能没有结果,开始写成true死都调不出来
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: