-
Notifications
You must be signed in to change notification settings - Fork 0
/
NoPrefixSet.java
62 lines (56 loc) · 1.43 KB
/
NoPrefixSet.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
/** https://www.hackerrank.com/challenges/no-prefix-set/problem #trie */
import java.util.Scanner;
public class NoPrefixSet {
static final int MAX = 'j' - 'a' + 1;
static class TrieNode {
TrieNode[] children;
boolean isEndOfWord;
TrieNode() {
children = new TrieNode[MAX];
isEndOfWord = false;
}
}
public static boolean addWord(TrieNode root, String word) {
TrieNode pTmp = root;
int length = word.length();
int idx, level;
boolean addNewNodeFlg = false;
boolean ret = true;
for (level = 0; level < length; level++) {
idx = word.charAt(level) - 'a';
if (pTmp.children[idx] == null) {
addNewNodeFlg = true;
pTmp.children[idx] = new TrieNode();
}
pTmp = pTmp.children[idx];
if (pTmp.isEndOfWord && level < length - 1) {
ret = false;
}
}
pTmp.isEndOfWord = true;
if (!addNewNodeFlg) {
ret = false;
}
return ret;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
TrieNode root = new TrieNode();
String word, ans = "";
for (int i = 0; i < n; i++) {
word = sc.next();
if (ans.isEmpty()) {
if (!addWord(root, word)) {
ans = word;
}
}
}
if (ans.isEmpty()) {
System.out.println("GOOD SET");
} else {
System.out.println("BAD SET");
System.out.println(ans);
}
}
}