Skip to content

Commit 8ea6aba

Browse files
authored
implement trie prefix tree solution
1 parent 7c9fc48 commit 8ea6aba

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
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+
*/

0 commit comments

Comments
 (0)