File tree 1 file changed +19
-18
lines changed
scripts/algorithms/S/Short Encoding of Words
1 file changed +19
-18
lines changed Original file line number Diff line number Diff line change
1
+ // Runtime: 23 ms (Top 85.71%) | Memory: 59.1 MB (Top 35.19%)
1
2
class Node {
2
3
private boolean flag ;
3
4
private Node [] children ;
4
-
5
+
5
6
public Node () {
6
7
flag = false ;
7
8
children = new Node [26 ];
8
9
Arrays .fill (children , null );
9
10
}
10
-
11
+
11
12
public boolean getFlag () {
12
13
return flag ;
13
14
}
14
-
15
+
15
16
public Node getChild (int index ) {
16
17
return children [index ];
17
18
}
18
-
19
+
19
20
public boolean hasChild (int index ) {
20
21
return children [index ] != null ;
21
22
}
22
-
23
+
23
24
public void setFlag (boolean flag ) {
24
25
this .flag = flag ;
25
26
}
26
-
27
+
27
28
public void makeChild (int index ) {
28
29
children [index ] = new Node ();
29
30
}
30
31
}
31
32
32
33
class Trie {
33
34
private Node root ;
34
-
35
+
35
36
public Trie () {
36
37
root = new Node ();
37
38
}
38
-
39
+
39
40
public int addWord (String word ) {
40
-
41
+
41
42
boolean flag = true ;
42
43
Node node = root ;
43
44
int count = 0 ;
44
-
45
+
45
46
for (int i = word .length () - 1 ; i >= 0 ; --i ) {
46
47
int index = (int ) word .charAt (i ) - 97 ;
47
-
48
+
48
49
if (!node .hasChild (index )) {
49
50
flag = false ;
50
51
node .makeChild (index );
51
52
}
52
-
53
+
53
54
node = node .getChild (index );
54
55
if (node .getFlag ()) {
55
56
node .setFlag (false );
56
57
count -= word .length () - i + 1 ;
57
-
58
+
58
59
if (i == 0 )
59
60
flag = false ;
60
61
}
61
62
}
62
-
63
+
63
64
if (!flag )
64
65
node .setFlag (true );
65
-
66
+
66
67
return flag ? count : count + 1 + word .length ();
67
68
}
68
69
}
@@ -71,11 +72,11 @@ class Solution {
71
72
public int minimumLengthEncoding (String [] words ) {
72
73
Trie trie = new Trie ();
73
74
int size = 0 ;
74
-
75
+
75
76
for (String word : words ) {
76
77
size += trie .addWord (word );
77
78
}
78
-
79
+
79
80
return size ;
80
81
}
81
- }
82
+ }
You can’t perform that action at this time.
0 commit comments