File tree Expand file tree Collapse file tree 1 file changed +64
-0
lines changed
implement-trie-prefix-tree Expand file tree Collapse file tree 1 file changed +64
-0
lines changed Original file line number Diff line number Diff line change 1+ // Time Complexity: O(n)
2+
3+ class TrieNode {
4+ children : { [ key : string ] : TrieNode } ;
5+ ending : boolean ;
6+
7+ constructor ( ending = false ) {
8+ this . children = { } ;
9+ this . ending = ending ;
10+ }
11+ }
12+
13+ class Trie {
14+ root : TrieNode ;
15+
16+ constructor ( ) {
17+ this . root = new TrieNode ( ) ;
18+ }
19+
20+ insert ( word : string ) : void {
21+ let node = this . root ;
22+
23+ for ( const ch of word ) {
24+ if ( ! ( ch in node . children ) ) {
25+ node . children [ ch ] = new TrieNode ( ) ;
26+ }
27+ node = node . children [ ch ] ;
28+ }
29+ node . ending = true ;
30+ }
31+
32+ search ( word : string ) : boolean {
33+ let node = this . root ;
34+
35+ for ( const ch of word ) {
36+ if ( ! ( ch in node . children ) ) {
37+ return false ;
38+ }
39+ node = node . children [ ch ] ;
40+ }
41+ return node . ending ;
42+ }
43+
44+ startsWith ( prefix : string ) : boolean {
45+ let node = this . root ;
46+
47+ for ( const ch of prefix ) {
48+ if ( ! ( ch in node . children ) ) {
49+ return false ;
50+ }
51+
52+ node = node . children [ ch ] ;
53+ }
54+ return true ;
55+ }
56+ }
57+
58+ /**
59+ * Your Trie object will be instantiated and called as such:
60+ * var obj = new Trie()
61+ * obj.insert(word)
62+ * var param_2 = obj.search(word)
63+ * var param_3 = obj.startsWith(prefix)
64+ */
You can’t perform that action at this time.
0 commit comments