class TrieNode {
public boolean isEnd;
public Map<Character, TrieNode> next;
public TrieNode() {
this.isEnd = false;
this.next = new HashMap<>();
}
}
class WordDictionary {
public TrieNode root;
public WordDictionary () {
this.root = new TrieNode();
}
public void addWord(String word) {
TrieNode rootTmp = root;
for (int index = 0; index < word.length(); index++) {
char c = word.charAt(index);
if (!rootTmp.next.containsKey(c)) {
TrieNode value = new TrieNode();
rootTmp.next.put(c, value);
}
rootTmp = rootTmp.next.get(c);
}
rootTmp.isEnd = true;
}
public boolean search(String word) {
int index = 0;
return dfs(word, root, index);
}
private boolean dfs(String word, TrieNode root, int index) {
int n = word.length();
if (n == index) {
return root.isEnd;
}
char c = word.charAt(index);
if (c == '.') {
for (TrieNode trieNode : root.next.values()) {
if (trieNode != null && dfs(word, trieNode, index + 1)) {
return true;
}
}
} else {
if (root.next.containsKey(c) && dfs(word, root.next.get(c), index + 1)) {
return true;
}
}
return false;
}
}
字典树的简单构造
于 2022-12-21 11:06:35 首次发布