File tree Expand file tree Collapse file tree
implement-trie-prefix-tree Expand file tree Collapse file tree Original file line number Diff line number Diff line change 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+ */
You canโt perform that action at this time.
0 commit comments