Skip to content

Commit c17404a

Browse files
committed
key_word suggation using trie algorithm
1 parent 3dceaa6 commit c17404a

File tree

1 file changed

+43
-11
lines changed

1 file changed

+43
-11
lines changed

trie/main.dart

Lines changed: 43 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,10 @@ class TrieNode {
66
children = {};
77
isEndOfWord = false;
88
}
9+
@override
10+
String toString() {
11+
return "{children: $children,isendofword: $isEndOfWord}";
12+
}
913
}
1014

1115
class SuffixTrie {
@@ -16,9 +20,7 @@ class SuffixTrie {
1620
}
1721

1822
void insert(String word) {
19-
for (int i = 0; i < word.length; i++) {
20-
insertHelper(word.substring(i), root!);
21-
}
23+
insertHelper(word, root!);
2224
}
2325

2426
void insertHelper(String word, TrieNode node) {
@@ -31,7 +33,7 @@ class SuffixTrie {
3133
if (!node.children!.containsKey(firstChar)) {
3234
node.children![firstChar] = TrieNode();
3335
}
34-
36+
// print(root.toString());
3537
insertHelper(word.substring(1), node.children![firstChar] as TrieNode);
3638
}
3739

@@ -51,6 +53,40 @@ class SuffixTrie {
5153

5254
return searchHelper(word.substring(1), node.children![firstChar] as TrieNode);
5355
}
56+
57+
List<String> searchSuggestions(String prefix) {
58+
TrieNode? prefixNode = findPrefixNode(prefix, root);
59+
print(prefixNode.toString());
60+
List<String> suggestions = [];
61+
if (prefixNode != null) {
62+
collectSuggestions(prefix, prefixNode, suggestions);
63+
}
64+
return suggestions;
65+
}
66+
67+
TrieNode? findPrefixNode(String prefix, TrieNode? node) {
68+
for (int i = 0; i < prefix.length; i++) {
69+
String char = prefix[i];
70+
if (node!.children!.containsKey(char)) {
71+
node = node.children![char] as TrieNode;
72+
} else {
73+
return null;
74+
}
75+
}
76+
return node;
77+
}
78+
79+
void collectSuggestions(
80+
String currentPrefix, TrieNode? node, List<String> suggestions) {
81+
if (node!.isEndOfWord!) {
82+
suggestions.add(currentPrefix);
83+
}
84+
85+
for (String char in node.children!.keys) {
86+
collectSuggestions(
87+
currentPrefix + char, node.children![char] as TrieNode, suggestions);
88+
}
89+
}
5490
}
5591

5692
void main() {
@@ -61,11 +97,7 @@ void main() {
6197
trie.insert("banana");
6298
trie.insert("car");
6399
trie.insert("carrot");
64-
65-
// Searching for words in the trie
66-
print(trie.search("apple")); // Output: true
67-
print(trie.search("banana")); // Output: true
68-
print(trie.search("car")); // Output: true
69-
print(trie.search("carrot")); // Output: true
70-
print(trie.search("cat")); // Output: false
100+
print(trie.searchSuggestions("ca"));
101+
print(trie.searchSuggestions("ban"));
102+
71103
}

0 commit comments

Comments
 (0)