File tree Expand file tree Collapse file tree 1 file changed +71
-0
lines changed
implement-trie-prefix-tree Expand file tree Collapse file tree 1 file changed +71
-0
lines changed Original file line number Diff line number Diff line change 1+ /*
2+ Time Complexity (n = length of word/prefix)
3+ - initialization: O(1)
4+ - insert: O(n)
5+ - search: O(n)
6+ - startsWith: O(n)
7+
8+ Space Complexity: O(n * c) (c = calls)
9+ - 길이 3인 알파벳 소문자 문자열의 가짓수 : 26^3 = 17,576
10+ - 길이 4인 알파벳 소문자 문자열의 가짓수 : 26^4 = 456,976
11+ 만약 n이 3 이하였다면, 3만 번의 call 동안 trie가 포화되어 공간 복잡도가 O(26 * n) = O(n) 이었을 것.
12+ 하지만 n이 2,000으로 충분히 크기 때문에 trie가 포화되지는 않을 것이므로, 공간 복잡도는 O(n * c).
13+ */
14+ class Trie {
15+
16+ class Node {
17+ public char val ;
18+ public boolean ends ;
19+ public HashMap <Character , Node > children ;
20+
21+ Node () {
22+ this .children = new HashMap <>();
23+ }
24+ }
25+
26+ public Node root ;
27+
28+ public Trie () {
29+ this .root = new Node ();
30+ }
31+
32+ public void insert (String word ) {
33+ Node curr = this .root ;
34+
35+ for (char ch : word .toCharArray ()) {
36+ curr = curr .children .computeIfAbsent (ch , c -> new Node ());
37+ curr .val = ch ;
38+ }
39+ curr .ends = true ;
40+ }
41+
42+ public boolean search (String word ) {
43+ Node curr = this .root ;
44+
45+ for (char ch : word .toCharArray ()) {
46+ curr = curr .children .get (ch );
47+ if (curr == null )
48+ return false ;
49+ }
50+ return curr .ends ;
51+ }
52+
53+ public boolean startsWith (String prefix ) {
54+ Node curr = this .root ;
55+
56+ for (char ch : prefix .toCharArray ()) {
57+ curr = curr .children .get (ch );
58+ if (curr == null )
59+ return false ;
60+ }
61+ return true ;
62+ }
63+ }
64+
65+ /**
66+ * Your Trie object will be instantiated and called as such:
67+ * Trie obj = new Trie();
68+ * obj.insert(word);
69+ * boolean param_2 = obj.search(word);
70+ * boolean param_3 = obj.startsWith(prefix);
71+ */
You can’t perform that action at this time.
0 commit comments