Skip to content

Commit 257c074

Browse files
committed
implement trie prefix tree solution
1 parent f5b97b2 commit 257c074

File tree

1 file changed

+96
-0
lines changed

1 file changed

+96
-0
lines changed
Lines changed: 96 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,96 @@
1+
/**
2+
[문제풀이]
3+
- Node를 만들자
4+
time: O(N), space: O(N)
5+
6+
[회고]
7+
노드를 만드는 접근은 맞았는데, 그 뒤로 안풀려서 해설을 보니 노드의 길이를 26으로 한다.
8+
이 부분에서 이해하기가 어려웠는데 아래를 보고 이해됐다.
9+
(root)
10+
├── c
11+
│ ├── a
12+
│ │ ├── t (end)
13+
│ │ └── r (end)
14+
└── d
15+
└── o
16+
└── g (end)
17+
18+
주어진 문자열을 핸들링하는 역할은 노드가 가지도록 노드 안에 솔루션을 구현했다.
19+
*/
20+
class Trie {
21+
Node root;
22+
23+
public Trie() {
24+
root = new Node();
25+
}
26+
27+
public void insert(String word) {
28+
root.insert(word);
29+
}
30+
31+
public boolean search(String word) {
32+
return root.search(word);
33+
}
34+
35+
public boolean startsWith(String prefix) {
36+
return root.startsWith(prefix);
37+
}
38+
}
39+
40+
class Node {
41+
Node[] nodes;
42+
boolean isEnd;
43+
44+
Node() {
45+
nodes = new Node[26];
46+
}
47+
48+
void insert(String word) {
49+
Node current = this;
50+
for (char ch : word.toCharArray()) {
51+
int index = ch - 'a';
52+
if (current.nodes[index] == null) {
53+
current.nodes[index] = new Node();
54+
}
55+
current = current.nodes[index];
56+
}
57+
current.isEnd = true;
58+
}
59+
60+
boolean search(String word) {
61+
Node current = this;
62+
for (char ch : word.toCharArray()) {
63+
int index = ch - 'a';
64+
if (current.nodes[index] == null) {
65+
return false;
66+
}
67+
current = current.nodes[index];
68+
}
69+
70+
if (current.isEnd) {
71+
return true;
72+
}
73+
return false;
74+
}
75+
76+
boolean startsWith(String prefix) {
77+
Node current = this;
78+
for (char ch : prefix.toCharArray()) {
79+
int index = ch - 'a';
80+
if (current.nodes[index] == null) {
81+
return false;
82+
}
83+
current = current.nodes[index];
84+
}
85+
return true;
86+
}
87+
}
88+
89+
/**
90+
* Your Trie object will be instantiated and called as such:
91+
* Trie obj = new Trie();
92+
* obj.insert(word);
93+
* boolean param_2 = obj.search(word);
94+
* boolean param_3 = obj.startsWith(prefix);
95+
*/
96+

0 commit comments

Comments
 (0)