-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy path2001 Shortest Prefixes.java
51 lines (50 loc) · 1.08 KB
/
2001 Shortest Prefixes.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
import java.util.*;
class Node {
Node[] nodes;
int num;
boolean isEnd;
Node() {
nodes = new Node[26];
isEnd = false;
num = 0;
}
public void insert(String str) {
Node node = this;
for (char c : str.toCharArray()) {
if (node.nodes[c - 'a'] == null) {
node.nodes[c - 'a'] = new Node();
}
node = node.nodes[c - 'a'];
node.num++;
}
node.isEnd = true;
}
public String search(String str) {
Node node = this;
StringBuilder sb = new StringBuilder();
for (char c : str.toCharArray()) {
node = node.nodes[c - 'a'];
sb.append(c);
if (node.num == 1) {
break;
}
}
return sb.toString();
}
}
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
List<String> list = new ArrayList<String>();
Node root = new Node();
while (in.hasNext()) {
String str = in.nextLine();
list.add(str);
root.insert(str);
}
for (String str : list) {
String rst = root.search(str);
System.out.println(str + " " + rst);
}
}
}