File tree Expand file tree Collapse file tree 1 file changed +42
-0
lines changed
solution/2400-2499/2416.Sum of Prefix Scores of Strings Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Trie {
2
+ constructor ( ) {
3
+ this . children = { } ;
4
+ this . cnt = 0 ;
5
+ }
6
+
7
+ insert ( w ) {
8
+ let node = this ;
9
+ for ( const c of w ) {
10
+ if ( ! node . children [ c ] ) {
11
+ node . children [ c ] = new Trie ( ) ;
12
+ }
13
+ node = node . children [ c ] ;
14
+ node . cnt ++ ;
15
+ }
16
+ }
17
+
18
+ search ( w ) {
19
+ let node = this ;
20
+ let ans = 0 ;
21
+ for ( const c of w ) {
22
+ if ( ! node . children [ c ] ) {
23
+ return ans ;
24
+ }
25
+ node = node . children [ c ] ;
26
+ ans += node . cnt ;
27
+ }
28
+ return ans ;
29
+ }
30
+ }
31
+
32
+ /**
33
+ * @param {string[] } words
34
+ * @return {number[] }
35
+ */
36
+ var sumPrefixScores = function ( words ) {
37
+ const trie = new Trie ( ) ;
38
+ for ( const w of words ) {
39
+ trie . insert ( w ) ;
40
+ }
41
+ return words . map ( w => trie . search ( w ) ) ;
42
+ } ;
You can’t perform that action at this time.
0 commit comments