File tree Expand file tree Collapse file tree 1 file changed +46
-0
lines changed
implement-trie-prefix-tree Expand file tree Collapse file tree 1 file changed +46
-0
lines changed Original file line number Diff line number Diff line change 1+ /*
2+ * 아이디어
3+ * 삽입된 전체 word를 저장해둔다. => wordSet
4+ * 삽입된 단어의 1글자 ~ 단어길이 글자 만큼을 전부 각각 prefix로 저장해둔다. => prefixSet
5+ * 중복처리를 위해 Set을 사용한다.
6+ */
7+ class Trie {
8+ wordSet : Set < string > ;
9+ prefixSet : Set < string > ;
10+
11+ constructor ( ) {
12+ this . wordSet = new Set ( ) ;
13+ this . prefixSet = new Set ( ) ;
14+ }
15+
16+ // TC: O(n) // n = word.length
17+ // SC: O(n)
18+ insert ( word : string ) : void {
19+ let result = "" ;
20+ for ( let i = 0 ; i < word . length ; i ++ ) {
21+ result += word [ i ] ;
22+ this . prefixSet . add ( result ) ;
23+ }
24+ this . wordSet . add ( word ) ;
25+ }
26+
27+ // TC: O(1)
28+ // SC: O(1)
29+ search ( word : string ) : boolean {
30+ return this . wordSet . has ( word ) ;
31+ }
32+
33+ // TC: O(1)
34+ // SC: O(1)
35+ startsWith ( prefix : string ) : boolean {
36+ return this . prefixSet . has ( prefix ) ;
37+ }
38+ }
39+
40+ /**
41+ * Your Trie object will be instantiated and called as such:
42+ * var obj = new Trie()
43+ * obj.insert(word)
44+ * var param_2 = obj.search(word)
45+ * var param_3 = obj.startsWith(prefix)
46+ */
You can’t perform that action at this time.
0 commit comments