-
Notifications
You must be signed in to change notification settings - Fork 119
/
Copy pathShort Encoding of Words.java
82 lines (63 loc) · 1.66 KB
/
Short Encoding of Words.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
// Runtime: 23 ms (Top 85.71%) | Memory: 59.1 MB (Top 35.19%)
class Node {
private boolean flag;
private Node[] children;
public Node () {
flag = false;
children = new Node[26];
Arrays.fill (children, null);
}
public boolean getFlag () {
return flag;
}
public Node getChild (int index) {
return children[index];
}
public boolean hasChild (int index) {
return children[index] != null;
}
public void setFlag (boolean flag) {
this.flag = flag;
}
public void makeChild (int index) {
children[index] = new Node();
}
}
class Trie {
private Node root;
public Trie () {
root = new Node();
}
public int addWord (String word) {
boolean flag = true;
Node node = root;
int count = 0;
for (int i = word.length () - 1; i >= 0; --i) {
int index = (int) word.charAt(i) - 97;
if (!node.hasChild (index)) {
flag = false;
node.makeChild (index);
}
node = node.getChild (index);
if (node.getFlag()) {
node.setFlag (false);
count -= word.length() - i + 1;
if (i == 0)
flag = false;
}
}
if (!flag)
node.setFlag (true);
return flag? count: count + 1 + word.length();
}
}
class Solution {
public int minimumLengthEncoding(String[] words) {
Trie trie = new Trie ();
int size = 0;
for (String word: words) {
size += trie.addWord (word);
}
return size;
}
}