解法
前缀树加上dfs
代码
class WordDictionary {
TrieNode root;
/** Initialize your data structure here. */
public WordDictionary() {
root=new TrieNode();
}
/** Adds a word into the data structure. */
public void addWord(String word) {
TrieNode cur=root;
for(int i=0;i<word.length();i++)
{
int temp=word.charAt(i)-'a';
if(cur.node[temp]==null)
{
cur.node[temp]=new TrieNode();
}
cur=cur.node[temp];
}
cur.isEnd=true;
}
public boolean search(String word) {
return f(word,0,root);
}
public boolean f(String word,int index,TrieNode node)
{
//base case
if(node==null)
{
return false;
}
else if(index==word.length())
{
return node.isEnd;
}
char temp=word.charAt(index);
if(temp=='.')
{
for(int i=0;i<26;i++)
{
if(node.node[i]!=null)
{
if(f(word,index+1,node.node[i])){
return true;
}
}
}
return false;
}else{
int tempint=temp-'a';
return f(word,index+1,node.node[tempint]);
}
}
}
class TrieNode{
TrieNode[] node;
boolean isEnd;
public TrieNode()
{
node=new TrieNode[26];
isEnd=false;
}
}
/**
* Your WordDictionary object will be instantiated and called as such:
* WordDictionary obj = new WordDictionary();
* obj.addWord(word);
* boolean param_2 = obj.search(word);
*/
京公网安备 11010502036488号