数据结构如图所示:题目要求符合Trie树特征。在Trie树的设计上,每个节点包括一个大小为26的数组,用来保存当前的值,和一个布尔型变量用来确定是否
单词已经结束。下图为单词aa,ab的结构图:
public class WordDictionary {
TrieNode tree = new TrieNode();
// Adds a word into the data structure.
public void addWord(String word) {
if(search(word)) return;
TrieNode root = tree;
char[] chars = word.toCharArray();
for(char c : chars) {
if(root.arr[c - 'a'] == null) {
TrieNode tmp = new TrieNode();
root.arr[c - 'a'] = tmp;
root = tmp;
}
else {
root = root.arr[c - 'a'];
}
}
root.isLeaf = true;//末尾添加leaf
}
public boolean search(String word) {
return df(tree, word, 0);
}
// 使用index处理‘.’
public boolean df(TrieNode root, String word, int index) {
if(word.length() == index && root.isLeaf) return true;
if(index >= word.length()) return false;
char c = word.charAt(index);
if(c == '.') {
for(int i = 0; i < 26; i++) {
if(root.arr[i] != null) {
if(df(root.arr[i], word, index + 1))
return true;
}
}
return false;
}
if(root.arr[c - 'a'] != null) {
return df(root.arr[c - 'a'], word, index + 1);
}
else
return false;
}
class TrieNode{
TrieNode[] arr;
boolean isLeaf;
public TrieNode(){
arr = new TrieNode[26];
}
}
}
// Your WordDictionary object will be instantiated and called as such:
// WordDictionary wordDictionary = new WordDictionary();
// wordDictionary.addWord("word");
// wordDictionary.search("pattern");