请你设计一个数据结构,支持 添加新单词 和 查找字符串是否与任何先前添加的字符串匹配 。
实现词典类 WordDictionary
:
WordDictionary()
初始化词典对象void addWord(word)
将word
添加到数据结构中,之后可以对它进行匹配bool search(word)
如果数据结构中存在字符串与word
匹配,则返回true
;否则,返回false
。word
中可能包含一些'.'
,每个.
都可以表示任何一个字母。
示例:
输入:
["WordDictionary","addWord","addWord","addWord","search","search","search","search"]
[[],["bad"],["dad"],["mad"],["pad"],["bad"],[".ad"],["b.."]]
输出:
[null,null,null,null,false,true,true,true]
解释:
WordDictionary wordDictionary = new WordDictionary();
wordDictionary.addWord("bad");
wordDictionary.addWord("dad");
wordDictionary.addWord("mad");
wordDictionary.search("pad"); // 返回 False
wordDictionary.search("bad"); // 返回 True
wordDictionary.search(".ad"); // 返回 True
wordDictionary.search("b.."); // 返回 True
提示:
1 <= word.length <= 25
addWord
中的word
由小写英文字母组成search
中的word
由 ‘.’ 或小写英文字母组成- 最多调用
104
次addWord
和search
//leetcode submit region begin(Prohibit modification and deletion)
class WordDictionary {
private Trie root;
public WordDictionary() {
this.root = new Trie();
}
public void addWord(String word) {
if (word == null || word.length() == 0) {
return;
}
Trie cur = this.root;
for (char ch : word.toCharArray()) {
if (cur.children[ch - 'a'] == null) {
cur.children[ch - 'a'] = new Trie();
}
cur = cur.children[ch - 'a'];
}
cur.hasWord = true;
}
public boolean search(String word) {
return matched(root, word.toCharArray(), 0);
}
private boolean matched(Trie trie, char[] charArr, int index) {
if (trie == null) {
return false;
}
if (index == charArr.length) {
return trie.hasWord;
}
char ch = charArr[index];
if (ch == '.') {
for (int i = 0; i < 26; i++) {
boolean match = matched(trie.children[i], charArr, index + 1);
if (match) {
return true;
}
}
return false;
} else {
return matched(trie.children[ch - 'a'], charArr, index + 1);
}
}
private class Trie {
Trie[] children;
boolean hasWord;
public Trie() {
this.children = new Trie[26];
this.hasWord = false;
}
}
}
/**
* Your WordDictionary object will be instantiated and called as such:
* WordDictionary obj = new WordDictionary();
* obj.addWord(word);
* boolean param_2 = obj.search(word);
*/
//leetcode submit region end(Prohibit modification and deletion)