forked from andreimaximov/algorithms
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathSolution.java
62 lines (50 loc) · 1.2 KB
/
Solution.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
import java.util.Scanner;
class TrieNode {
public boolean eos;
public TrieNode[] children;
public static int RANGE = 'j' - 'a' + 1;
public TrieNode() {
this.eos = true;
this.children = new TrieNode[RANGE];
}
}
class Trie {
private TrieNode root;
public Trie() {
this.root = new TrieNode();
}
public boolean add(String word) {
TrieNode node = root;
int index = 0;
while (index < word.length()) {
node.eos = false;
char c = word.charAt(index);
int i = c - 'a';
if (node.children[i] == null) {
node.children[i] = new TrieNode();
} else if (node.children[i].eos || index == word.length() - 1) {
return false;
}
node = node.children[i];
index++;
}
return true;
}
}
public class Solution {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int N = scanner.nextInt();
scanner.nextLine();
Trie trie = new Trie();
for (int i = 0; i < N; i++) {
String word = scanner.nextLine();
if (!trie.add(word)) {
System.out.println("BAD SET");
System.out.println(word);
return;
}
}
System.out.println("GOOD SET");
}
}