https://leetcode-cn.com/problems/US1pGT/
思路
- 这个题思路有点妙 用递归函数来做~
- 递归函数返回遍历至此是否符合题目中的条件,参数是字符串、遍历到的索引index,此时的前缀树的层root,以及是否更改
- 如果root是null,证明没有该结点,所以返回false
- 如果index和word.length()相等,那么说明遍历到最后一层了,只有此前修改过且这个结点的isWord是true,才能说明是一个可以替换的字符串
- 下面的代码理解起来也比较简单~
import java.util.Arrays;
class Trie {
class TrieNode {
boolean isWord;
TrieNode[] children;
TrieNode() {
children = new TrieNode[26];
}
}
TrieNode root;
Trie() {
root = new TrieNode();
}
void buildDict(String s) {
TrieNode cur = root;
for (char ch : s.toCharArray()) {
if (null == cur.children[ch - 'a'])
cur.children[ch - 'a'] = new TrieNode();
cur = cur.children[ch - 'a'];
}
cur.isWord = true;
}
boolean dfs(String word, TrieNode root, int index, boolean isChanged) {
if (null == root)
return false;
if (index == word.length())
return isChanged && root.isWord;
boolean result = false;
if (isChanged) {
if (null != root.children[word.charAt(index) - 'a']) {
return dfs(word, root.children[word.charAt(index) - 'a'], index + 1, true);
} else
return false;
} else {
for (int i = 0; i < 26; i++) {
if (null != root.children[i]) {
if (word.charAt(index) - 'a' == i)
result |= dfs(word, root.children[i], index + 1, false);
else
result |= dfs(word, root.children[i], index + 1, true);
}
}
}
return result;
}
}
public class MagicDictionary {
Trie trie;
/**
* Initialize your data structure here.
*/
public MagicDictionary() {
trie = new Trie();
}
public void buildDict(String[] dictionary) {
Arrays.stream(dictionary).toList().forEach(trie::buildDict);
}
public boolean search(String searchWord) {
return trie.dfs(searchWord,trie.root,0,false);
}
}