您的位置:首页 > 其它

LeetCode Add and Search Word - Data structure design Trie

2015-11-12 09:57 513 查看
思路:

根据hint应该用trie树,否则肯定超时。

java code:

public class WordDictionary {
class TrieNode {
boolean isLeaf;
TrieNode[] children = new TrieNode[26];

public TrieNode() {
}
}
private TrieNode root = new TrieNode();
// Adds a word into the data structure.
public void addWord(String word) {
TrieNode node = root;
for(char c : word.toCharArray()) {
if(node.children[c - 'a'] == null) {
node.children[c - 'a'] = new TrieNode();
}
node = node.children[c - 'a'];
}
node.isLeaf = true;
}

// Returns if the word is in the data structure. A word could
// contain the dot character '.' to represent any one letter.
private boolean dfs(String word, TrieNode cur) {
if(cur == null) return false;
if(word.length() == 0) return cur.isLeaf;
TrieNode[] children = cur.children;
char c = word.charAt(0);
if(c == '.') {
for(TrieNode child : children) {
if(child != null && dfs(word.substring(1), child)) {
return true;
}
}
return false;
}else if(children[c - 'a'] != null) {
return dfs(word.substring(1), children[c - 'a']);
}else {
return false;
}
}
public boolean search(String word) {
return dfs(word, root);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: