TS写前缀树的插入和检索

前缀树结构可以存储字符串并对其进行检索

前缀树节点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;
    }
}
  • 8
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值