208. Implement Trie (Prefix Tree)

Implement a trie with insertsearch, and startsWith methods.

Note:

You may assume that all inputs are consist of lowercase letters a-z.


题目原意:

实现字典树数据结构,包含插入,查找,前缀的方法。

注意:

可以假定所有输入由小写字母a-z组成。


解题思路:

字典树的每个节点至多由26个英文字母组成。

每个节点有两个属性:键值,是否为word的boolean值,以及由哈希表构成的字典。


代码如下:

首先构造函数,初始值为

this.root = {key: 'root', isWord: false};

/**
 * @constructor
 * Initialize your data structure here.
 */
var TrieNode = function (key) {
    return {
        key: key,
        isWord: false
    }
};

var Trie = function () {
    this.root = TrieNode('root');
};

Insert 函数

遍历word的每一个字符,若字符在tree中不存在,则将字符插入新节点。每次插入新字符都要更新tree的原值。tree始终指向的是当前遍历的字符的值。

比如插入‘oath’ 之后,tree值变为:

{ key: 'root',

isWord: false,

o: {key: 'o', isWord: false, a:{ key: 'a', 

isWord: false, 

t: { key: 't',

isWord: false,

h: { key: 'h',

isWord: true }

}}}}

/**
 * @param {string} word
 * @return {void}
 * Inserts a word into the trie.
 */
Trie.prototype.insert = function (word) {
    var tree = this.root;
    for (var i in word) {
        var cur = word[i];
        if (!tree[cur]) {
            tree[cur] = new TrieNode(cur);
        }
        tree = tree[cur];
    }
    tree.isWord = true;
};

search 函数

tree作为由root节点开始的字典,遍历单词的每一个字符,若当前字符在字典中出现,则进入下一层字典。直至当前word遍历完毕,字典isWord为true时返回true。其他情况均为false。

/**
 * @param {string} word
 * @return {boolean}
 * Returns if the word is in the trie.
 */
Trie.prototype.search = function (word) {
    var tree = this.root;
    for (var i in word) {
        if (!tree[word[i]]) {
            return false;
        }
        tree = tree[word[i]];
    }
    if (tree.isWord) {
        return true;
    } else {
        return false;
    }
};

startsWith 函数

和search函数类似,唯一不同的是startsWith只是比较前段部分的单词,因此可以省去最后是否为word的判断。

/**
 * @param {string} prefix
 * @return {boolean}
 * Returns if there is any word in the trie
 * that starts with the given prefix.
 */
Trie.prototype.startsWith = function (prefix) {
    var tree = this.root;
    for (var i in prefix) {
        if (!tree[prefix[i]]) {
            return false;
        }
        tree = tree[prefix[i]];
    }
    return true;
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值