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