前綴樹:理論知識不做贅述,直接看代碼
1-Node節點、
樹是由一個個節點組建而來,那前綴樹的節點應該包含哪些基本信息呢:
a-以當前節點作爲末尾節點的次數
b-以當前節點作爲中間節點的次數
c-當前節點的後續節點
代碼如下:
class TrieNode{
int path;
int end;
TrieNode [] nexts ;
TrieNode(){
path = 0 ;
end = 0;
nexts = new TrieNode[26];
}
}
當前構建的node節點用來統計單詞信息,而字母只有26個,所以nexts可以用長度爲26的數組代替。此處根據情況也可以使用HashMap<char,TrieNode>
2-樹結構
樹結構必須包含的基本信息
a-根節點root
b-插入方法insert
c-搜索方法search,該方法應該返回包含被查找單詞的個數
d-前綴計數方法,該方法應該返回以搜索word作爲前綴的單詞的個數
3-方法
a-insert
將單詞轉化爲charArray,將Array中的每個char元素添加到數中
因爲之前使用了長度爲26的數組來作爲next,所以每個字節的index可以通過index = char[i] - 'a'得到。
將對應位置構建出TrieNode
增加沿途節點的path值和尾節點的end值
public void insert(String word){
if(word == null){
return;
}
char [] chars = word.toCharArray();
TrieNode node = root;
int index = 0;
for(int i = 0; i < chars.length; i++){
index = chars[i] - 'a';
if(node.nexts[index] == null){
node.nexts[index] = new TrieNode();
}
node = node.nexts[index];
node.path ++;
}
node.end++;
}
b-search
同插入的邏輯基本相同。
給定的word轉化爲charArray,一次查詢每個char的next節點是否存在,如果循環過程中任意一個不存在則返回0,若循環到最後返回最後一個節點的end值。
public int search(String word){
if(word == null){
return 0;
}
char [] chars = word.toCharArray();
TrieNode node = root;
int index = 0;
for(int i = 0; i < chars.length; i++){
index = chars[i] - 'a';
if(node.nexts[index] == null){
return 0;
}
node = node.nexts[index];
}
return node.end;
}
delete和prefixNum同理。代碼如下:
public void delete(String word){
if(search(word) != 0 && word == null){
return;
}
char [] chars = word.toCharArray();
int index = 0;
TrieNode node = root;
for(int i = 0; i < chars.length; i++){
index = chars[i] - 'a';
if(--node.nexts[index].path == 0){
node.nexts[index] = null;
return;
}
node = node.nexts[index];
}
node.end--;
}
public int prefixNum(String word){
if(word == null){
return 0;
}
TrieNode node = root;
char [] chars = word.toCharArray();
int index = 0;
for(int i = 0; i < chars.length; i++){
index = chars[i] - 'a';
if(node.nexts[index] == null){
return 0;
}
node = node.nexts[index];
}
return node.path;
}