https://leetcode.cn/problems/design-add-and-search-words-data-structure/description/?envType=study-plan-v2&envId=top-interview-150
思路:就是然我们设计一个字典树,和上一题基本一样,之前使用的是树的方式来构建字典树。
class Main{
class WordDictionary {
private WordDictionary[] children;
private boolean isEnd;
public WordDictionary() {
this.children = new WordDictionary[26];
this.isEnd = false;
}
public void addWord(String word) {
WordDictionary node = this;
for (int i = 0; i < word.length(); i++) {
char ch = word.charAt(i);
int index = ch - 'a';
if (node.children[index] == null) {
node.children[index] = new WordDictionary();
}
node = node.children[index];
}
node.isEnd = true;
}
public boolean search(String word) {
WordDictionary node = this;
return search2(node, word, 0);
}
public boolean search2(WordDictionary node, String word, int index) {
if(index == word.length()) {
return node.isEnd;
}
//遇到'.' 的逻辑:遍历该层的所有非空节点只要所有情况中存在匹配情况就返回true(意思就是只有true才是终点)
char ch = word.charAt(index);
if(ch == '.') {
for(WordDictionary child : node.children) {
if( child != null) {
if(search2(child, word, index + 1)) {
return true;
}
}
}
} else {
if(node.children[ch - 'a'] != null && search2(node.children[ch - 'a'], word, index + 1)) {
return true;
}
}
return false;
}
}
public static void main(String[] args) {
Main main = new Main();
WordDictionary wordDictionary = main.new WordDictionary();
wordDictionary.addWord("bad");
wordDictionary.addWord("dad");
wordDictionary.addWord("mad");
System.out.println(wordDictionary.search("pad")); // return false
System.out.println(wordDictionary.search("bad")); // return true
System.out.println(wordDictionary.search(".ad")); // return true
System.out.println(wordDictionary.search("b..")); // return true
}
}