您的位置:首页 > 其它

Add and Search Word - Data structure design

2016-07-10 12:39 393 查看
public class WordDictionary {

private class TrieNode {
TrieNode[] children = new TrieNode[26];
boolean isExisted;
}

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;
for (int i = 0; i < word.length(); i++) {
int c = word.charAt(i) - 'a';
if (node.children[c] == null) {
TrieNode child = new TrieNode();
node.children[c] = child;
node = child;
} else {
node = node.children[c];
}
}
node.isExisted = 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 == null) {
return false;
}
return helper(word, root, 0);
}

private boolean helper(String word, TrieNode node, int pos) {
if (pos == word.length() && node.isExisted) {
return true;
}
if (pos >= word.length()) {
return false;
}
char c = word.charAt(pos);
if (c == '.') {
for (int i = 0; i < 26; i++) {
if (node.children[i] != null) {
if (helper(word, node.children[i], pos + 1)) {
return true;
}
}
}
} else {
int idx = c - 'a';
if (node.children[idx] != null) {
if (helper(word, node.children[idx], pos + 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");
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: