File tree Expand file tree Collapse file tree 1 file changed +82
-0
lines changed
implement-trie-prefix-tree Expand file tree Collapse file tree 1 file changed +82
-0
lines changed Original file line number Diff line number Diff line change 1+ // trieNode 클래스 선언
2+ // child = {}, end = false 로 초기화
3+ class TrieNode {
4+ constructor ( child = { } , end = false ) {
5+ this . child = child ;
6+ this . end = end ;
7+ }
8+ }
9+
10+ // Trie함수의 root는 TrieNode의 객체
11+ var Trie = function ( ) {
12+ this . root = new TrieNode ( ) ;
13+ } ;
14+
15+ /**
16+ * @param {string } word
17+ * @return {void }
18+ */
19+ // 단어 삽입
20+ Trie . prototype . insert = function ( word ) {
21+ // 현재 = 최상단으로 초기화
22+ let current = this . root ;
23+
24+ // 단어를 반복하면서 없으면 TrieNode에 추가
25+ for ( const char of word ) {
26+ if ( ! current . child [ char ] ) {
27+ current . child [ char ] = new TrieNode ( ) ;
28+ }
29+ current = current . child [ char ] ;
30+ }
31+
32+ // 반복이 끝나면 end true
33+ current . end = true ;
34+ } ;
35+
36+ /**
37+ * @param {string } word
38+ * @return {boolean }
39+ */
40+ // 단어 탐색
41+ Trie . prototype . search = function ( word ) {
42+ // 현재위치 = 최상단으로
43+ let current = this . root ;
44+
45+ // 반복하면서 단어찾기
46+ for ( const char of word ) {
47+ if ( current . child [ char ] ) {
48+ current = current . child [ char ] ;
49+ }
50+ else {
51+ return false ;
52+ }
53+ }
54+ return current . end ;
55+
56+ } ;
57+
58+ /**
59+ * @param {string } prefix
60+ * @return {boolean }
61+ */
62+ Trie . prototype . startsWith = function ( prefix ) {
63+ let current = this . root ;
64+ for ( const char of prefix ) {
65+ if ( current . child [ char ] ) {
66+ current = current . child [ char ] ;
67+ }
68+ else {
69+ return false ;
70+ }
71+ }
72+
73+ return true ;
74+ } ;
75+
76+ /**
77+ * Your Trie object will be instantiated and called as such:
78+ * var obj = new Trie()
79+ * obj.insert(word)
80+ * var param_2 = obj.search(word)
81+ * var param_3 = obj.startsWith(prefix)
82+ */
You can’t perform that action at this time.
0 commit comments