构造trie树即可
比较坑的是next数组的判空
class MagicDictionary {
Node root;
boolean isSuccess;
public MagicDictionary() {
root = new Node();
}
public void buildDict(String[] dictionary) {
for (String s : dictionary) {
build(root, s, 0);
}
}
public boolean search(String searchWord) {
isSuccess = false;
dfs(root, searchWord, 0, false);
return isSuccess;
}
void build(Node node, String s, int index) {
if (node.next == null) {
node.next = new Node[26];
}
char c = s.charAt(index);
int key = c - 'a';
if (node.next[key] == null) {
node.next[key] = new Node();
}
Node next = node.next[key];
next.c = c;
if (index == s.length() - 1) {
next.end = true;
return;
}
build(next, s, index + 1);
}
void dfs(Node node, String s, int index, boolean isChange) {
if (isSuccess) {
return;
}
if (index == s.length()) {
if (node.end && isChange) {
isSuccess = true;
}
return;
}
char c = s.charAt(index);
int key = c - 'a';
Node[] next = node.next;
if(next == null) {
return;
}
// 没有使用过万能权
if (!isChange) {
for (int i = 0; i < 26; i++) {
if (next[i] != null && i != key) {
dfs(next[i], s, index + 1, true);
}
}
}
if (next[key] != null) {
dfs(next[key], s, index + 1, isChange);
}
}
}
class Node {
char c;
Node[] next;
boolean end;
}