File tree Expand file tree Collapse file tree 1 file changed +40
-0
lines changed
implement-trie-prefix-tree Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Trie {
2
+
3
+ final int n;
4
+ final children = < int , Trie > {};
5
+ bool ended = false ;
6
+
7
+ Trie ([this .n = 0 ]);
8
+
9
+ void insert (String word) {
10
+ Trie u = this ;
11
+ for (int rune in word.runes) {
12
+ u = u.children
13
+ .putIfAbsent (rune, () => Trie (rune));
14
+ }
15
+ u.ended = true ;
16
+ }
17
+
18
+ bool search (String word) => _search (word)? .ended ?? false ;
19
+
20
+ bool startsWith (String prefix) => _search (prefix) != null ;
21
+
22
+ Trie ? _search (String word) {
23
+ Trie ? u = this ;
24
+ for (int rune in word.runes) {
25
+ u = u! .children[rune];
26
+ if (u == null ) {
27
+ return null ;
28
+ }
29
+ }
30
+ return u;
31
+ }
32
+ }
33
+
34
+ /**
35
+ * Your Trie object will be instantiated and called as such:
36
+ * Trie obj = Trie();
37
+ * obj.insert(word);
38
+ * bool param2 = obj.search(word);
39
+ * bool param3 = obj.startsWith(prefix);
40
+ */
You can’t perform that action at this time.
0 commit comments