forked from luliyucoordinate/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0820.java
33 lines (29 loc) · 908 Bytes
/
0820.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
class Solution {
public int minimumLengthEncoding(String[] words) {
Trie root = new Trie();
for (int i = 0; i < words.length; i++) root.insert(words[i], i);
int res = 0;
for (Map.Entry<Node, Integer> it : root.nodes.entrySet()) {
if (it.getKey().next.isEmpty()) {
res += words[it.getValue()].length() + 1;
}
}
return res;
}
}
class Node {
public Map<Character, Node> next = new HashMap();
}
class Trie {
private Node root = new Node();
public Map<Node, Integer> nodes = new HashMap();
public void insert(String str, int id) {
Node cur = root;
for (int i = str.length() - 1; i >= 0; i--) {
char j = str.charAt(i);
if (!cur.next.containsKey(j)) cur.next.put(j, new Node());
cur = cur.next.get(j);
}
nodes.put(cur, id);
}
}