-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution.cs
More file actions
68 lines (62 loc) · 1.67 KB
/
Solution.cs
File metadata and controls
68 lines (62 loc) · 1.67 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
public class Solution
{
public int[] SumPrefixScores(string[] words)
{
List<int> ans = [];
Dictionary<string, int> dp = [];
Trie trie = new();
foreach (string word in words)
{
trie.Insert(word);
}
foreach (string word in words)
{
if (!dp.ContainsKey(word))
{
dp.Add(word, trie.CountScorePrefix(word));
}
ans.Add(dp[word]);
}
//Console.WriteLine($"[{string.Join(",", dp)}]");
return [.. ans];
}
public class TrieNode
{
public int Count { get; set; }
public TrieNode[] children = new TrieNode[26];
}
public class Trie
{
private readonly TrieNode root = new();
public void Insert(string word)
{
TrieNode node = root;
foreach (char character in word.ToCharArray())
{
int idx = character - 'a';
if (node.children[idx] == null)
{
node.children[idx] = new TrieNode();
}
node = node.children[idx];
node.Count++;
}
}
public int CountScorePrefix(string word)
{
TrieNode node = root;
int count = 0;
foreach (char character in word.ToCharArray())
{
int idx = character - 'a';
if (node.children[idx] == null)
{
break;
}
node = node.children[idx];
count += node.Count;
}
return count;
}
}
}