本题的关键在于两点:首先是构造Trie,并实现相关add操作;其次是通过dfs来对整个Trie进行搜索和遍历,来进行匹配。
具体代码如下(Java实现,关于trie的相关知识,大家可以自行百度~)
public class Trie{
public Trie[] children;
public boolean isEnd;
Trie(){
this.children = new Trie[26];
this.isEnd = false;
}
public void insert(String word){
Trie root = this;
for(char c : word.toCharArray()){
if(root.children[c - 'a'] == null){
root.children[c - 'a'] = new Trie();
}
root = root.children[c - 'a'];
}
root.isEnd = true;
}
}
class WordDictionary {
Trie T = new Trie();
public WordDictionary() {
}
public void addWord(String word) {
T.insert(word);
}
public boolean search(String word) {
return dfs(word, T);
}
public boolean dfs(String word, Trie rt){
// 递归终止条件
if(word.length() == 0){
return rt.isEnd;
}
// 第一个字符是字母
if (word.charAt(0) != '.'){
int ID = (int)(word.charAt(0) - 'a');
if(rt.children[ID] != null){
if(dfs(word.substring(1), rt.children[ID]) == true){
return true;
}
}
return false;
}
// 第一个字符是.
for(int ID=0;ID<26;ID++){
if(rt.children[ID]!=null){
if(dfs(word.substring(1), rt.children[ID]) == true){
return true;
}
}
}
return false;
}
}
/**
* Your WordDictionary object will be instantiated and called as such:
* WordDictionary obj = new WordDictionary();
* obj.addWord(word);
* boolean param_2 = obj.search(word);
*/