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