-
Notifications
You must be signed in to change notification settings - Fork 1
/
1268-search-suggestions-system.cs
49 lines (43 loc) · 1.34 KB
/
1268-search-suggestions-system.cs
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
public class Solution {
public IList<IList<string>> SuggestedProducts(string[] products, string searchWord) {
var trie = new Trie();
trie.Build(products);
return trie.Search(searchWord);
}
}
public class Trie{
List<string> suggestions;
Trie[] next;
public Trie(){
suggestions = new List<string>();
next = new Trie[26];
}
public void AddSuggestion(string word){
suggestions.Add(word);
suggestions = suggestions.OrderBy(w => w).Take(3).ToList();
}
public void Build(string[] words){
foreach(var word in words){
var curr = next;
foreach(var ch in word){
if(curr[ch-'a'] == null) curr[ch-'a'] = new Trie();
curr[ch-'a'].AddSuggestion(word);
curr = curr[ch-'a'].next;
}
}
}
public IList<IList<string>> Search(string word){
var result = new List<IList<string>>();
var curr = next;
foreach(var ch in word){
if(curr == null || curr[ch-'a'] == null){
result.Add([]);
curr = null; // mark it so that now onwards no substring will be checked
continue;
}
result.Add(curr[ch-'a'].suggestions);
curr = curr[ch-'a'].next;
}
return result;
}
}