class WordDictionary {
private Node root;
private class Node{
public boolean isWord;
public TreeMap<Character,Node>next;//多叉树
public Node(boolean isWord){
this.isWord=isWord;
next=new TreeMap<>();
}
public Node(){
// this(false);相当于调用构造器NOde(boolen is Word)
this.isWord=false;
next=new TreeMap<>();
}
}
/** Initialize your data structure here. */
public WordDictionary() {
root=new Node();
}
/** Adds a word into the data structure. */
public void addWord(String word) {
_insert(root,0,word);
}
// 从cur 节点构建word[index:]求word[0:]
public void _insert(Node cur,int i,String word){
if(i==word.length())
{
cur.isWord=true;
return ;
}
//cur 走到了word最后一个字符,不一定是叶子结点,如panda(中pan 为一个单词)
char c=word.charAt(i);
if(cur.next.get(c)==null)
cur.next.put(c,new Node());
cur=cur.next.get(c);//走到c结点
_insert(cur,i+1,word);
}
/** 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(word,root,0);
}
public boolean _search(String word,Node cur,int i){
if(i==word.length()) return cur.isWord;
char c=word.charAt(i);
if(c!='.'){
if(cur.next.get(c)==null) return false;
cur=cur.next.get(c);
return _search(word, cur, i+1);
}
else {
for(char nextchar:cur.next.keySet()){
if(_search(word,cur.next.get(nextchar),i+1)) return true;
}
return 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 211. 添加与搜索单词 - 数据结构设计
最新推荐文章于 2024-06-21 11:09:05 发布