用單詞查找樹,實現方法有很多,但是看了算法第4版的實現發現代碼真的簡潔強大。
可以先看這篇文章:單詞查找樹
這裏搜索單詞只需要判斷true或false,不需要全部匹配,稍稍修改了下。
class WordDictionary {
private Node root;
private static int R = 26;
static class Node {
private boolean isWordEnd = false;
private Node[] next = new Node[R];
}
/**
* Initialize your data structure here.
*/
public WordDictionary() {
}
/**
* Adds a word into the data structure.
*/
public void addWord(String word) {
root = put(root, word, 0);
}
private Node put(Node x, String word, int d) {
if (x == null) {
x = new Node();
}
if (d == word.length()) {
x.isWordEnd = true;
return x;
}
char c = word.charAt(d);
x.next[c - 'a'] = put(x.next[c - 'a'], word, d + 1);
return x;
}
/**
* 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 x, String pat, int d) {
if (x == null) {
return false;
}
if (d == pat.length()) {
return x.isWordEnd;
}
char c = pat.charAt(d);
if (c == '.') {
// 搜索所有節點
for (int i = 0; i < R; i++) {
if (search(x.next[i], pat, d + 1)) {
return true;
}
}
} else {
return search(x.next[c - 'a'], pat, d + 1);
}
return false;
}
}