-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsearch_suggestions_system.dart
More file actions
57 lines (47 loc) · 1.46 KB
/
Copy pathsearch_suggestions_system.dart
File metadata and controls
57 lines (47 loc) · 1.46 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
// https://leetcode.com/problems/search-suggestions-system/
class SearchSuggestionsSystem {
List<List<String>> suggestedProducts(List<String> products, String searchWord) {
final root = _TrieNode();
for (final product in products) {
_addProductsToTrie(root, product);
}
final result = <List<String>>[];
_TrieNode? currentNode = root;
for (var i = 0; i < searchWord.length; i++) {
final ch = searchWord[i];
if (currentNode != null && currentNode.children.containsKey(ch)) {
currentNode = currentNode.children[ch];
result.add(List.from(currentNode!.suggestions));
} else {
currentNode = null;
result.add([]);
}
}
return result;
}
}
void _addProductsToTrie(_TrieNode root, String product) {
var node = root;
for (var i = 0; i < product.length; i++) {
final ch = product[i];
node.children.putIfAbsent(ch, () => _TrieNode());
node = node.children[ch]!;
if (!node.suggestions.contains(product)) {
_addSuggestionToProduct(node, product);
}
}
}
void _addSuggestionToProduct(_TrieNode node, String product) {
if (node.suggestions.length < 3) {
node.suggestions.add(product);
node.suggestions.sort();
} else if (product.compareTo(node.suggestions.last) < 0) {
node.suggestions.add(product);
node.suggestions.sort();
node.suggestions.removeLast();
}
}
class _TrieNode {
var children = <String, _TrieNode>{};
var suggestions = <String>[];
}