思路:
就是前缀树。如果碰到点符号就遍历好了,只要有一个返回true就返回true。。
class TrieNode {
// Initialize your data structure here.
TrieNode charecters[];
boolean end;
public TrieNode() {
charecters=new TrieNode[26];
end=false;
}
}
public class WordDictionary {
private TrieNode root;
public WordDictionary() {
root = new TrieNode();
root.charecters=new TrieNode[26];
}
// Adds a word into the data structure.
public void addWord(String word) {
int n=word.length();
TrieNode temp=root;
for(int i=0;i<n;i++)
{
if(temp.charecters[word.charAt(i)-'a']==null)
{
temp.charecters[word.charAt(i)-'a']=new TrieNode();
}
temp=temp.charecters[word.charAt(i)-'a'];
}
temp.end=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 searchHelp(word, 0,root);
}
public boolean searchHelp(String word,int currentIndex,TrieNode root)
{
if(currentIndex==word.length())
{
return root.end==true;
}
char targetChar=word.charAt(currentIndex);
if(targetChar=='.')
{
for(int i=0;i<26;i++)
{
if(root.charecters[i]!=null&&searchHelp(word, currentIndex+1, root.charecters[i]))
{
return true;
}
}
}
else
{
if(root.charecters[targetChar-'a']!=null)
{
return searchHelp(word, currentIndex+1, root.charecters[targetChar-'a']);
}
}
return false;
}
}
// Your WordDictionary object will be instantiated and called as such:
// WordDictionary wordDictionary = new WordDictionary();
// wordDictionary.addWord("word");
// wordDictionary.search("pattern");