前缀树结构可以存储字符串并对其进行检索
前缀树节点TrieNode:
export class TrieNode {
pass: number = 0; //经过其的字符串个数
end: number = 0; //以其为字符串结尾的字符串个数
nexts: Array<TrieNode>; //假设字符串中只包含26种字母,该节点指向的下一个节点
//nexts:Map<string,TrieNode>; //如果字符串所包含的不止有26个字母,则用Map
constructor() {
this.nexts = new Array<TrieNode>(26);//假设字符串中只包含26种字母
//this.nexts = new Map<string,TrieNode>();//如果字符串所包含的不止有26个字母
}
}
前缀树结构
/**
* 前缀树(假设字符串只包含26种字母)
*/
export class Trie {
public root: TrieNode; //前缀树头节点
constructor() {
this.root = new TrieNode();
}
...
}
前缀树插入
/**
* 插入字符串word
*/
insert(word: string) {
if (word == null) return
let node = this.root;
node.pass++;
let index = 0
for (let i = 0; i < word.length; i++) {
index = word.charCodeAt(i) - 'a'.charCodeAt(0);
if (node.nexts[index] == null) {
node.nexts[index] = new TrieNode();
}
node = node.nexts[index];
node.pass++;
}
node.end++;
}
前缀树检索
/**
* 检查word字串被插入了几次
*/
search(word: string) {
if (word == null) return 0;
let node = this.root;
let index = 0;
for (let i = 0; i < word.length; i++) {
index = word.charCodeAt(i) - 'a'.charCodeAt(0);
if (node.nexts[index] == null) return 0;
node = node.nexts[index];
}
return node.end;
}
/**
* 检查以word字串作为前缀的字串的插入次数
*/
preFixNumber(word: string) {
if (word == null) return 0;
let node = this.root;
let index = 0;
for (let i = 0; i < word.length; i++) {
index = word.charCodeAt(i) - 'a'.charCodeAt(0);
if (node.nexts[index] == null) return 0;
node = node.nexts[index];
}
return node.pass;
}
}