[DA] Trie

Trie

๋ฌธ์ž์—ด์„ ์ €์žฅํ•˜๊ณ  ํšจ์œจ์ ์œผ๋กœ ํƒ์ƒ‰ํ•˜๊ธฐ ์œ„ํ•œ ํŠธ๋ฆฌ ํ˜•ํƒœ์˜ ์ž๋ฃŒ๊ตฌ์กฐ

๊ฒ€์ƒ‰์–ด ์ž๋™์™„์„ฑ, ์‚ฌ์ „ ์ฐพ๊ธฐ ๋“ฑ์— ์‘์šฉ

๊ตฌ์กฐ

  1. ๋ฃจํŠธ๋Š” ๋น„์–ด์žˆ๋‹ค.
  2. ๊ฐ ๊ฐ„์„ (๋งํฌ)์€ ์ถ”๊ฐ€๋  ๋ฌธ์ž๋ฅผ ํ‚ค๋กœ ๊ฐ€์ง
  3. ๊ฐ ์ •์ ์€ ์ด์ „ ์ •์ ์˜ ๊ฐ’ + ๊ฐ„์„ ์˜ ํ‚ค๋ฅผ ๊ฐ’์œผ๋กœ ๊ฐ€์ง
  4. ํ•ด์‹œ ํ…Œ์ด๋ธ”, ์—ฐ๊ฒฐ ๋ฆฌ์ŠคํŠธ๋ฅผ ์ด์šฉํ•˜์—ฌ ๊ตฌํ˜„
class Node {
  constructor(value = '') {
    this.value = value;
    this.children = new Map();
  }
}

class Trie {
  constructor() {
    this.root = new Node();
  }

  insert(string) {
    let currentNode = this.root;

    for (const char of string) {
      if (!currentNode.children.has(char)) {
        currentNode.children.set(char, new Node(currentNode.value + char));
      }

      currentNode = currentNode.children.get(char);
    }
  }

  has(string) {
    let currentNode = this.root;

    for (const char of string) {
      if (!currentNode.children.has(char)) {
        return false;
      }
      currentNode = currentNode.children.get(char);
    }

    return true;
  }
}

const trie = new Trie();
trie.insert('bee');
trie.insert('tea');
console.log(trie.has('bee'));
console.log(trie.has('test'));

Categories:

Updated:

Leave a comment