浅谈Trie树(字典树)
理解:如下五个字符串的插入过程,abc是一个插入的字符串,所以占用了0 1 2 这三行。abd 占用了1 2 4行,是因为ab这个前缀和abc共用了,但是d是第一次出现,所以会按顺序占用下一行没有被占用的行,所以占用的是第四行,依次类推。相同前缀的字符串,比如abd,abh,aba,他们的第三个字符都会放在第三行,因为他们前一个字符都相同。这样按照顺序占用行,使得每一个字符串会有第一“唯一路径”,这就使得插入和查询能正确进行。
* abc 1 2 3
* abd 1 2 4
* abh 1 2 5
* aba 1 2 6
* bd 7 8
*
* 1 7 0 0 0 0 0 0
* 0 2 0 0 0 0 0 0
* 6 0 3 4 0 0 0 5
* 0 0 0 0 0 0 0 0
* 0 0 0 0 0 0 0 0
* 0 0 0 0 0 0 0 0
* 0 0 0 0 0 0 0 0
* 0 0 8 0 0 0 0 0
Java版代码
public class Test {
public int tot = 0;
public int[][] tries = new int[1000000][26];
public void insert(String word) {
int rt = 0;
for (int i = 0; i < word.length(); i++){
int n = word.charAt(i) - 'a';
if (tries[rt][n] == 0) {
tries[rt][n] = ++tot;
}
rt = tries[rt][n];
}
}
public boolean search(String word) {
int rt = 0;
for (int i = 0; i < word.length(); i++) {
int n = word.charAt(i) - 'a';
if (tries[rt][n] == 0) return false;
rt = tries[rt][n];
}
return true;
}
public static void main(String[] args) {
Test q = new Test();
q.insert("abc");
q.insert("abd");
q.insert("abh");
q.insert("aba");
q.insert("bc");
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 26; j++) {
System.out.print(tries[i][j] + " ");
}
System.out.println();
}
/**
* abc 1 2 3
* abd 1 2 4
* abh 1 2 5
* aba 1 2 6
* bd 7 8
*
* 1 7 0 0 0 0 0 0
* 0 2 0 0 0 0 0 0
* 6 0 3 4 0 0 0 5
* 0 0 0 0 0 0 0 0
* 0 0 0 0 0 0 0 0
* 0 0 0 0 0 0 0 0
* 0 0 0 0 0 0 0 0
* 0 0 8 0 0 0 0 0
*/
}
}