File tree Expand file tree Collapse file tree 1 file changed +52
-0
lines changed
implement-trie-prefix-tree Expand file tree Collapse file tree 1 file changed +52
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Trie {
2
+ /**
3
+ 1. understanding
4
+ - Trie data structure
5
+ - To process at most 3 * 10^4 calls in proper time, each call must be under O(N), where N is the length of word.
6
+ - insert: insert data into Trie
7
+ - search: find data from inserted Datas
8
+ - startsWith: find
9
+ 2. strategy
10
+ - a) use list to save inserted words
11
+ - insert: O(1)
12
+ - search: O(L * N), where L is the length of list, N is the length of each words.
13
+ - startsWith: O(L * N)
14
+ - total call to be 3 * 10^4, i assume each method call count at most 10^4 or linear correlation in 10^4 scale.
15
+ - so, L <= 10^4, N <= 10^4
16
+ - space: O(L * N)
17
+ - it is enough to pass, but there are duplicates in space and also in excution count.
18
+ - b)
19
+ */
20
+
21
+ private List <String > words ;
22
+ public Trie () {
23
+ words = new ArrayList <>();
24
+ }
25
+
26
+ public void insert (String word ) {
27
+ words .add (word );
28
+ }
29
+
30
+ public boolean search (String word ) {
31
+ for (String w : words ) {
32
+ if (w .equals (word )) return true ;
33
+ }
34
+ return false ;
35
+ }
36
+
37
+ public boolean startsWith (String prefix ) {
38
+ for (String w : words ) {
39
+ if (w .indexOf (prefix ) == 0 ) return true ;
40
+ }
41
+ return false ;
42
+ }
43
+ }
44
+
45
+ /**
46
+ * Your Trie object will be instantiated and called as such:
47
+ * Trie obj = new Trie();
48
+ * obj.insert(word);
49
+ * boolean param_2 = obj.search(word);
50
+ * boolean param_3 = obj.startsWith(prefix);
51
+ */
52
+
You can’t perform that action at this time.
0 commit comments