[JavaScript 刷题] 树 - 实现前缀树, leetcode 208

[JavaScript 刷题] 树 - 实现前缀树, leetcode 208

github repo 地址: https://github.com/GoldenaArcher/js_leetcode,Github 的目录 大概 会更新的更勤快一些。

题目地址:208. Implement Trie (Prefix Tree)

题目

如下:

A trie (pronounced as “try”) or prefix tree is a tree data structure used to efficiently store and retrieve keys in a dataset of strings. There are various applications of this data structure, such as autocomplete and spellchecker.

Implement the Trie class:

  • Trie() Initializes the trie object.
  • void insert(String word) Inserts the string word into the trie.
  • boolean search(String word) Returns true if the string word is in the trie (i.e., was inserted before), and false otherwise.
  • boolean startsWith(String prefix) Returns true if there is a previously inserted string word that has the prefix prefix, and false otherwise.

解题思路

前缀树 trie 中讲了一下 trie 的一点儿应用场景以及基础实现,这里对于 trie 的实现会使用 前缀树 trie 中的。

insertsearchstartsWith 基本逻辑都是遍历 trie。

insert 在遍历中将该单词添加到 trie 中。

searchstartsWith 的逻辑基本完全一致,唯一有区别的就是返回值。search 返回当前搜索的单词是否存在于 trie 中,即在结束的时候,这个节点必须是一个单词的结尾。startsWith 只要判断该前缀是否存在于 trie 中即可。

使用 JavaScript 解题

class TrieNode {
    
    
  constructor(val) {
    
    
    this.val = val;
    this.children = [];
    this.isWord = false;
  }

  getIdx(ch) {
    
    
    return ch.charCodeAt(0) - "a".charCodeAt(0);
  }

  hasChild(ch) {
    
    
    return this.children[this.getIdx(ch)] !== undefined;
  }

  createChild(ch) {
    
    
    this.children[this.getIdx(ch)] = new TrieNode(ch);
  }

  getChild(ch) {
    
    
    return this.children[this.getIdx(ch)];
  }
}

var Trie = function () {
    
    
  this.trie = new TrieNode("");
};

/**
 * @param {string} word
 * @return {void}
 */
Trie.prototype.insert = function (word) {
    
    
  let root = this.trie;
  for (const ch of word) {
    
    
    if (root.hasChild(ch));
    else root.createChild(ch);

    root = root.getChild(ch);
  }

  root.isWord = true;
};

/**
 * @param {string} word
 * @return {boolean}
 */
Trie.prototype.search = function (word) {
    
    
  let root = this.trie;
  for (const ch of word) {
    
    
    if (!root.hasChild(ch)) return false;
    root = root.getChild(ch);
  }
  return root.isWord;
};

/**
 * @param {string} prefix
 * @return {boolean}
 */
Trie.prototype.startsWith = function (prefix) {
    
    
  let root = this.trie;
  for (const ch of prefix) {
    
    
    if (!root.hasChild(ch)) return false;
    root = root.getChild(ch);
  }

  return true;
};

猜你喜欢

转载自blog.csdn.net/weixin_42938619/article/details/125720739