- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNoPrefixSet.java
More file actions
Latest commit
108 lines (87 loc) · 2.96 KB
/
Copy pathNoPrefixSet.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.
*/
importjava.io.*;
importjava.math.*;
importjava.security.*;
importjava.text.*;
importjava.util.*;
importjava.util.concurrent.*;
importjava.util.function.*;
importjava.util.regex.*;
importjava.util.stream.*;
importstaticjava.util.stream.Collectors.joining;
importstaticjava.util.stream.Collectors.toList;
classBranchNode
{
Map<Character, BranchNode> next = newHashMap<>();
booleanisEndofWord = false;
}
classResult
{
/*
* Complete the 'noPrefix' function below.
*
* The function accepts STRING_ARRAY words as parameter.
*/
publicstaticvoidnoPrefix(List<String> words)
{
// Write your code here
BranchNoderoot = newBranchNode();
for(Stringword : words)
{
BranchNodecurrentNode = root;
booleanisBadSet = false;
intn = word.length();
for(inti = 0; i < n; i++)
{
charch = word.charAt(i);
if(currentNode.isEndofWord)
{
System.out.println("BAD SET");
System.out.println(word);
return;
}
currentNode = currentNode.next.computeIfAbsent(ch, k -> newBranchNode());
}
if(!currentNode.next.isEmpty() || currentNode.isEndofWord)
{
System.out.println("BAD SET");
System.out.println(word);
return;
}
currentNode.isEndofWord = true;
}
System.out.println("GOOD SET");
}
}
publicclassSolution
{
publicstaticvoidmain(String[] args) throwsIOException
{
BufferedReaderbufferedReader = newBufferedReader(newInputStreamReader(System.in));
intn = Integer.parseInt(bufferedReader.readLine().trim());
List<String> words = IntStream.range(0, n).mapToObj(i ->
{
try
{
returnbufferedReader.readLine();
}
catch (IOExceptionex)
{
thrownewRuntimeException(ex);
}
})
.collect(toList());
Result.noPrefix(words);
bufferedReader.close();
}
}