分析
暴力的时间复杂度是
递归+前缀树
n*len(s)
class MagicDictionary {
Trie trie;
public MagicDictionary() {
trie = new Trie();
}
public void buildDict(String[] dictionary) {
for (String s : dictionary) {
Trie cur = trie;
for (char c : s.toCharArray()) {
int index = c - 'a';
if (cur.children[index] == null) {
cur.children[index] = new Trie();
}
cur = cur.children[index];
}
cur.end = true;
}
}
public boolean search(String searchWord) {
return dfs(searchWord,0,trie,1);
}
public boolean dfs (String word, int poi, Trie cur, int count) {
if (count < 0 || cur == null) {
return false;
}
if (poi == word.length()) {
return count == 0 && cur.end;
}
int c = word.charAt(poi) - 'a';
boolean ans = false;
for (int i = 0; i < 26; i++) {
if (i == c) {
ans |= dfs(word,poi+1,cur.children[i],count);
} else {
ans |= dfs(word,poi+1,cur.children[i],count-1);
}
if (ans) {
return true;
}
}
return false;
}
}
class Trie {
boolean end;
Trie[] children;
Trie() {
end = false;
children = new Trie[26];
}
}
/**
* Your MagicDictionary object will be instantiated and called as such:
* MagicDictionary obj = new MagicDictionary();
* obj.buildDict(dictionary);
* boolean param_2 = obj.search(searchWord);
*/