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("cat");
trie.insert("can");
console.log(trie.has("cat")); // true
console.log(trie.has("caq")); // false
console.log(trie.has("can")); // true
console.log(trie.has("cab")); // false
프로그래머스 데브코스 교육 내용을 바탕으로 정리한 글 입니다.