File tree Expand file tree Collapse file tree 1 file changed +47
-0
lines changed
solution/2400-2499/2416.Sum of Prefix Scores of Strings Expand file tree Collapse file tree 1 file changed +47
-0
lines changed Original file line number Diff line number Diff line change @@ -337,6 +337,53 @@ function sumPrefixScores(words: string[]): number[] {
337337}
338338```
339339
340+ #### JavaScript
341+
342+ ``` js
343+ class Trie {
344+ constructor () {
345+ this .children = {};
346+ this .cnt = 0 ;
347+ }
348+
349+ insert (w ) {
350+ let node = this ;
351+ for (const c of w) {
352+ if (! node .children [c]) {
353+ node .children [c] = new Trie ();
354+ }
355+ node = node .children [c];
356+ node .cnt ++ ;
357+ }
358+ }
359+
360+ search (w ) {
361+ let node = this ;
362+ let ans = 0 ;
363+ for (const c of w) {
364+ if (! node .children [c]) {
365+ return ans;
366+ }
367+ node = node .children [c];
368+ ans += node .cnt ;
369+ }
370+ return ans;
371+ }
372+ }
373+
374+ /**
375+ * @param {string[]} words
376+ * @return {number[]}
377+ */
378+ var sumPrefixScores = function (words ) {
379+ const trie = new Trie ();
380+ for (const w of words) {
381+ trie .insert (w);
382+ }
383+ return words .map (w => trie .search (w));
384+ };
385+ ```
386+
340387<!-- tabs: end -->
341388
342389<!-- solution: end -->
You can’t perform that action at this time.
0 commit comments