【前缀树】211. 添加与搜索单词 - 数据结构设计
题目:
请你设计一个数据结构,支持 添加新单词 和 查找字符串是否与任何先前添加的字符串匹配 。
实现词典类 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"); // return False
wordDictionary.search("bad"); // return True
wordDictionary.search(".ad"); // return True
wordDictionary.search("b.."); // return True
解答:
前缀树+递归
`//前缀树+递归
class WordDictionary {
private final int SIZE = 26;
private WordDictionary[] children = new WordDictionary[SIZE];
private boolean isEnd = false;
/** Initialize your data structure here. */
public WordDictionary() {
}
/** Adds a word into the data structure. */
public void addWord(String word) {
WordDictionary tmp = this;
for(int i = 0;i<word.length();i++){
int idx = word.charAt(i) - 'a';
if(tmp.children[idx] == null){
tmp.children[idx] = new WordDictionary();
}
tmp = tmp.children[idx];
}
tmp.isEnd = 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 recurSearch(word,0,this);
}
public boolean recurSearch(String word,int cur,WordDictionary root){
WordDictionary tmp = root;
for(int i = cur;i<word.length();i++){
if(word.charAt(i) == '.'){
//如果当前节点为'.',可以递归(跳过当前节点)
for(int j = 0;j<26;j++){
if(tmp.children[j]!=null){
if(recurSearch(word,i+1,tmp.children[j])){
return true;
}
}
}
return false;
}
int idx = word.charAt(i) - 'a';
if(tmp.children[idx] == null){
return false;
}
tmp = tmp.children[idx];
}
return tmp.isEnd;
}
}
`

浙公网安备 33010602011771号