// å®ä¹èç¹ class Node { constructor(isWord=false) { this.isWord = isWord; this.next = new Map(); } } // åå ¸æ module.exports = class Trie{ constructor() { this.root = new Node(); this.size = 0; } // è·åTrieä¸åå¨çåè¯æ°é getSize() { return this.size; } // åTrie䏿·»å ä¸ä¸ªæ°çåè¯word add(word) { // ééå½åæ³ï¼å符串ææå符 let cur = this.root; for(let i = 0;i < word.length; i++) { let c = word.charAt(i); if(cur.next.get(c) === undefined) { cur.next.set(c, new Node()); } cur = cur.next.get(c); // èµ°å°ä¸ä¸ä¸ªèç¹ } // è¿ä¸ªèç¹ä»¥åä¸è¡¨ç¤ºåè¯ç»å°¾ if(!cur.isWord) { cur.isWord = true; this.size++; } } // æ¥è¯¢åè¯wordæ¯å¦å¨Trieä¸ contains(word) { let cur = root; for(let i = 0;i < word.length; i++) { let c = wrod.charAt(i); if(cur.next.get(c) === null) return false; cur = cur.next.get(c); } // æ¯å¦trie䏿pandaï¼æ¥panãæ¥å°èç¹ï¼ä½æ¯å¹¶æ²¡æè¿ä¸ªåè¯ return cur.isWord; } // åç¼æ¥è¯¢ isPrefix(prefix) { let cur = this.root; for(let i = 0; i < prefix.length; i++) { let c = prefix.charAt(i); if(cur.next.get(c) === undefined) return false; cur = cur.next.get(c); } return true; } }