-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNoPrefixSet.java
More file actions
108 lines (87 loc) · 2.96 KB
/
NoPrefixSet.java
File metadata and controls
108 lines (87 loc) · 2.96 KB
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
/*
No Prefix Set
You are given a list of strings consisting only of lowercase letters. A set of strings is considered a GOOD SET if no string in the set is a prefix of another string.
If any string is a prefix of another, print BAD SET followed by the first offending string.
Input
The first line contains an integer n (1 ≤ n ≤ 100,000), the number of strings.
The next n lines each contain a string words[i] (1 ≤ |words[i]| ≤ 100), composed of lowercase letters.
Output
Print GOOD SET if the strings form a good set.
If there is a bad set, print BAD SET followed by the offending string on the next line.
*/
import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;
import java.util.regex.*;
import java.util.stream.*;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;
class BranchNode
{
Map<Character, BranchNode> next = new HashMap<>();
boolean isEndofWord = false;
}
class Result
{
/*
* Complete the 'noPrefix' function below.
*
* The function accepts STRING_ARRAY words as parameter.
*/
public static void noPrefix(List<String> words)
{
// Write your code here
BranchNode root = new BranchNode();
for(String word : words)
{
BranchNode currentNode = root;
boolean isBadSet = false;
int n = word.length();
for(int i = 0; i < n; i++)
{
char ch = word.charAt(i);
if(currentNode.isEndofWord)
{
System.out.println("BAD SET");
System.out.println(word);
return;
}
currentNode = currentNode.next.computeIfAbsent(ch, k -> new BranchNode());
}
if(!currentNode.next.isEmpty() || currentNode.isEndofWord)
{
System.out.println("BAD SET");
System.out.println(word);
return;
}
currentNode.isEndofWord = true;
}
System.out.println("GOOD SET");
}
}
public class Solution
{
public static void main(String[] args) throws IOException
{
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(bufferedReader.readLine().trim());
List<String> words = IntStream.range(0, n).mapToObj(i ->
{
try
{
return bufferedReader.readLine();
}
catch (IOException ex)
{
throw new RuntimeException(ex);
}
})
.collect(toList());
Result.noPrefix(words);
bufferedReader.close();
}
}