Skip to content

Commit d212055

Browse files
committed
implement-trie-prefix-tree solutions
1 parent 427ed1c commit d212055

1 file changed

Lines changed: 68 additions & 0 deletions

File tree

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
class Trie {
2+
class TrieNode {
3+
TrieNode[] children;
4+
boolean isEnd;
5+
6+
public TrieNode() {
7+
children = new TrieNode[26]; // a ~ z
8+
isEnd = false;
9+
}
10+
}
11+
12+
private TrieNode root;
13+
14+
public Trie() {
15+
root = new TrieNode();
16+
}
17+
18+
public void insert(String word) {
19+
TrieNode node = root;
20+
21+
for(char c: word.toCharArray()) {
22+
int index = c - 'a';
23+
//์ฒ˜์Œ ๋“ค์–ด์˜ค๋Š” ๋‹จ์–ด๋Š” node ์ƒ์„ฑ
24+
if(node.children[index] == null) {
25+
node.children[index] = new TrieNode();
26+
}
27+
//๋‹ค์Œ ๋…ธ๋“œ๋กœ ์ด๋™
28+
node = node.children[index];
29+
}
30+
//๋‹จ์–ด์˜ ๋ ํ‘œ์‹œ
31+
node.isEnd = true;
32+
}
33+
34+
public boolean search(String word) {
35+
TrieNode node = root;
36+
for(char c: word.toCharArray()) {
37+
int index = c - 'a';
38+
//์กด์žฌํ•˜์ง€ ์•Š์œผ๋ฉด false return
39+
if(node.children[index] == null) {
40+
return false;
41+
}
42+
//๋‹ค์Œ ๋…ธ๋“œ๋กœ ์ด๋™
43+
node = node.children[index];
44+
}
45+
return node.isEnd;
46+
}
47+
48+
public boolean startsWith(String prefix) {
49+
//์ค‘๊ฐ„์— null์„ ์•ˆ๋งŒ๋‚˜๋ฉด true ๋ฐ˜ํ™˜
50+
TrieNode node = root;
51+
for(char c: prefix.toCharArray()) {
52+
int index = c - 'a';
53+
if(node.children[index] == null) {
54+
return false;
55+
}
56+
node = node.children[index];
57+
}
58+
return true;
59+
}
60+
}
61+
62+
/**
63+
* Your Trie object will be instantiated and called as such:
64+
* Trie obj = new Trie();
65+
* obj.insert(word);
66+
* boolean param_2 = obj.search(word);
67+
* boolean param_3 = obj.startsWith(prefix);
68+
*/

0 commit comments

Comments
ย (0)