211. 添加与搜索单词 - 数据结构设计
import java.util.TreeMap;
class WordDictionary {
class Node{
boolean isWord;
TreeMap<Character, Node> next;
public Node(){
isWord = false;
next = new TreeMap<>();
}
}
Node root;
public WordDictionary() {
root = new Node();
}
public void addWord(String word) {
Node cur = root;
for (int i = 0; i < word.length(); i++) {
char c = word.charAt(i);
if (cur.next.get(c) == null){
cur.next.put(c, new Node());
}
cur = cur.next.get(c);
}
cur.isWord = true;
}
public boolean search(String word){
return match(root, word, 0);
}
/**
* 传入要查找的字典树的根节点root,要查询的字符串word和要查询的字符串的第几个字符index
* 当index到达末尾时,说明遍历完了,这时只需判断这个节点的isWord是否为真
* 如果c是.,那么要对该节点所有的子节点进行遍历,只要有一种情况符合就返回true
* Map类的keySet()方法获取所有的键
*/
private boolean match(Node root, String word, int index){
if (word.length() == index){
return root.isWord;
}
char c = word.charAt(index);
if (c != '.'){
if (root.next.get(c) == null){
return false;
}
else {
return match(root.next.get(c), word, index + 1);
}
}
else {
for (char nextChar : root.next.keySet()){
if (match(root.next.get(nextChar), word, index + 1)){
return true;
}
}
return false;
}
}
}
https://leetcode-cn.com/problems/design-add-and-search-words-data-structure/