/* * @lc app=leetcode id=208 lang=javascript * * [208] Implement Trie (Prefix Tree) * * https://leetcode.com/problems/implement-trie-prefix-tree/description/ * * algorithms * Medium (36.93%) * Total Accepted: 172K * Total Submissions: 455.5K * Testcase Example: '["Trie","insert","search","search","startsWith","insert","search"]\n[[],["apple"],["apple"],["app"],["app"],["app"],["app"]]'
* * Implement a trie with insert, search, and startsWith methods. * * Example: * * * Trie trie = new Trie(); * * trie.insert("apple"); * trie.search("apple"); // returns true * trie.search("app"); // returns false * trie.startsWith("app"); // returns true * trie.insert("app"); * trie.search("app"); // returns true * * * Note: * * * You may assume that all inputs are consist of lowercase letters a-z. * All inputs are guaranteed to be non-empty strings. * * */functionTrieNode(val) {this.val = val;this.children = [];this.isWord =false;}functioncomputeIndex(c) {returnc.charCodeAt(0) -"a".charCodeAt(0);}/** * Initialize your data structure here. */varTrie=function () {this.root =newTrieNode(null);};/** * Inserts a word into the trie. * @param{string} word * @return{void} */Trie.prototype.insert=function (word) {let ws =this.root;for (let i =0; i <word.length; i++) {constc= word[i];constcurrent=computeIndex(c);if (!ws.children[current]) {ws.children[current] =newTrieNode(c); } ws =ws.children[current]; }ws.isWord =true;};/** * Returns if the word is in the trie. * @param{string} word * @return{boolean} */Trie.prototype.search=function (word) {let ws =this.root;for (let i =0; i <word.length; i++) {constc= word[i];constcurrent=computeIndex(c);if (!ws.children[current]) returnfalse; ws =ws.children[current]; }returnws.isWord;};/** * Returns if there is any word in the trie that starts with the given prefix. * @param{string} prefix * @return{boolean} */Trie.prototype.startsWith=function (prefix) {let ws =this.root;for (let i =0; i <prefix.length; i++) {constc= prefix[i];constcurrent=computeIndex(c);if (!ws.children[current]) returnfalse; ws =ws.children[current]; }returntrue;};/** * Your Trie object will be instantiated and called as such: * var obj = new Trie() * obj.insert(word) * var param_2 = obj.search(word) * var param_3 = obj.startsWith(prefix) */