leetcode 链接:https://leetcode-cn.com/problems/design-add-and-search-words-data-structure/
题目
解法
public class WordDictionary {
private class Node {
private static final int size = 26;
// 当前节点是否为某个单词的末位
boolean isWord;
// 指向子节点
Node[] next;
public Node(boolean isWord) {
this.isWord = isWord;
next = new Node[size];
}
public Node() {
this(false);
}
public boolean containsKey(char ch) {
return next[ch - 'a'] != null;
}
public Node get(char ch) {
return next[ch - 'a'];
}
public void put(char ch, Node node) {
next[ch - 'a'] = node;
}
}
// 根节点
private final Node root;
/**
* Initialize your data structure here.
*/
public WordDictionary() {
this.root = new Node();
}
/**
* Adds a word into the data structure.
*/
public void addWord(String word) {
Node curr = root;
for (int i = 0; i < word.length(); i++) {
char ch = word.charAt(i);
if (!curr.containsKey(ch)) {
curr.put(ch, new Node());
}
curr = curr.get(ch);
}
curr.isWord = true;
}
/**
* Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter.
*/
public boolean search(String word) {
return search(root, word, 0);
}
private boolean search(Node curr, String word, int index) {
if (word.length() == index) {
// 到达末尾
return curr.isWord;
}
char ch = word.charAt(index);
if (ch == '.') {
// 遍历所有的节点一一匹配,如果能够终止于true,说明能够匹配成功
for (Node node : curr.next) {
if (node != null && search(node, word, index + 1)) {
return true;
}
}
return false;
} else if (!curr.containsKey(ch)) {
return false;
} else {
return search(curr.get(ch), word, index + 1);
}
}
}