class MagicDictionary {
static class TrieNode{
TrieNode[] children;
boolean isWord;
public TrieNode(){
children = new TrieNode[26];
}
}
private TrieNode root;
public MagicDictionary() {
root = new TrieNode();
}
public void buildDict(String[] dictionary) {
for(String word : dictionary){
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.isWord = true;
}
}
public boolean search(String searchWord) {
return dfs(root,searchWord,0,0);
}
public boolean dfs(TrieNode root,String searchWord,int edit,int index){
if(root == null){
return false;
}
if(root.isWord && index == searchWord.length() && edit == 1){
return true;
}
if(index < searchWord.length() && edit <= 1){
boolean found = false;
for(int i = 0;i < 26 && !found;i++){
int next = i == searchWord.charAt(index) - 'a' ? edit : edit + 1;
found = dfs(root.children[i],searchWord,next,index + 1);
}
return found;
}
return false;
}
}
|