-
Notifications
You must be signed in to change notification settings - Fork 111
/
solution.java
87 lines (48 loc) · 1.75 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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
sc.nextLine();
Node head = new Node();
for(int i = 0; i < n ; i++){
String line = sc.nextLine();
if(!head.add(line)){
System.out.println("BAD SET");
System.out.println(line);
sc.close();
return;
}
}
System.out.println("GOOD SET");
}
/* We are given N strings, we have to print "GOOD SET" if none of the strings in the set are prefix of any other string in the set.
If any string is a prefix of any other string in the set then we are supposed to print "BAD SET" followed by the FIRST string for which such condition is detected in the set. */
static class Node{
Map<Character, Node> map = new HashMap<>();
boolean isComplete;
public boolean add(String word){
return add(word,0);
}
private boolean add(String word, int index){
if(isComplete){
return false;
}
if(index == word.length()){
isComplete = true;
return true;
}
Node child = map.get(word.charAt(index));
if(child == null){
child = new Node();
map.put(word.charAt(index),child);
}else if(index + 1 == word.length()){
return false;
}
return child.add(word,index+1);
}
}
}