-
Notifications
You must be signed in to change notification settings - Fork 112
/
1268-SearchSuggestionsSystem.cs
58 lines (49 loc) · 1.65 KB
/
1268-SearchSuggestionsSystem.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
50
51
52
53
54
55
56
57
58
//-----------------------------------------------------------------------------
// Runtime: 360ms
// Memory Usage: 50 MB
// Link: https://leetcode.com/submissions/detail/369509717/
//-----------------------------------------------------------------------------
using System;
using System.Collections.Generic;
namespace LeetCode
{
public class _1268_SearchSuggestionsSystem
{
public IList<IList<string>> SuggestedProducts(string[] products, string searchWord)
{
Array.Sort(products);
var root = new TrieNode();
foreach (string prod in products)
{
var curr = root;
foreach (char c in prod)
{
if (curr.Children[c - 'a'] == null)
curr.Children[c - 'a'] = new TrieNode();
curr = curr.Children[c - 'a'];
if (curr.Suggestion.Count < 3)
curr.Suggestion.Add(prod);
}
}
List<IList<string>> res = new List<IList<string>>();
TrieNode curr2 = root;
foreach (char c in searchWord)
{
if (curr2 != null)
curr2 = curr2.Children[c - 'a'];
res.Add(curr2 == null ? new List<string>() : curr2.Suggestion);
}
return res;
}
private class TrieNode
{
public List<string> Suggestion;
public TrieNode[] Children;
public TrieNode()
{
Suggestion = new List<string>();
Children = new TrieNode[26];
}
}
}
}