@@ -6,6 +6,10 @@ class TrieNode {
6
6
children = {};
7
7
isEndOfWord = false ;
8
8
}
9
+ @override
10
+ String toString () {
11
+ return "{children: $children ,isendofword: $isEndOfWord }" ;
12
+ }
9
13
}
10
14
11
15
class SuffixTrie {
@@ -16,9 +20,7 @@ class SuffixTrie {
16
20
}
17
21
18
22
void insert (String word) {
19
- for (int i = 0 ; i < word.length; i++ ) {
20
- insertHelper (word.substring (i), root! );
21
- }
23
+ insertHelper (word, root! );
22
24
}
23
25
24
26
void insertHelper (String word, TrieNode node) {
@@ -31,7 +33,7 @@ class SuffixTrie {
31
33
if (! node.children! .containsKey (firstChar)) {
32
34
node.children! [firstChar] = TrieNode ();
33
35
}
34
-
36
+ // print(root.toString());
35
37
insertHelper (word.substring (1 ), node.children! [firstChar] as TrieNode );
36
38
}
37
39
@@ -51,6 +53,40 @@ class SuffixTrie {
51
53
52
54
return searchHelper (word.substring (1 ), node.children! [firstChar] as TrieNode );
53
55
}
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
+ }
54
90
}
55
91
56
92
void main () {
@@ -61,11 +97,7 @@ void main() {
61
97
trie.insert ("banana" );
62
98
trie.insert ("car" );
63
99
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
+
71
103
}
0 commit comments