Skip to content

Commit 3e9b8d7

Browse files
authored
Create PasswordCracker.java
1 parent 2efeff2 commit 3e9b8d7

File tree

1 file changed

+78
-0
lines changed

1 file changed

+78
-0
lines changed

PasswordCracker.java

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
import java.io.*;
2+
import java.math.*;
3+
import java.security.*;
4+
import java.text.*;
5+
import java.util.*;
6+
import java.util.concurrent.*;
7+
import java.util.function.*;
8+
import java.util.regex.*;
9+
import java.util.stream.*;
10+
import static java.util.stream.Collectors.joining;
11+
import static java.util.stream.Collectors.toList;
12+
13+
class Result {
14+
15+
// We keep a set of failed tracks,
16+
// so whenever we got with a shorter loginAttempt that has been previously reached
17+
// we know that our current path is going to end on a "WRONG PASSWORD"
18+
public static boolean passwordCracker(
19+
List<String> passwords,
20+
String loginAttempt,
21+
Set<String> failed,
22+
LinkedList<String> result) {
23+
24+
if (loginAttempt.isEmpty()) return true;
25+
if (failed.contains(loginAttempt)) return false;
26+
27+
for(String password: passwords){
28+
if (loginAttempt.startsWith(password)) {
29+
failed.add(loginAttempt);
30+
result.add(password);
31+
if (passwordCracker(passwords, loginAttempt.substring(password.length()), failed, result)) return true;
32+
33+
result.removeLast();
34+
}
35+
}
36+
37+
return false;
38+
39+
}
40+
41+
}
42+
43+
public class Solution {
44+
public static void main(String[] args) throws IOException {
45+
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
46+
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));
47+
48+
int t = Integer.parseInt(bufferedReader.readLine().trim());
49+
50+
IntStream.range(0, t).forEach(tItr -> {
51+
try {
52+
int n = Integer.parseInt(bufferedReader.readLine().trim());
53+
54+
List<String> passwords = Stream.of(bufferedReader.readLine().replaceAll("\\s+$", "").split(" "))
55+
.collect(toList());
56+
57+
String loginAttempt = bufferedReader.readLine();
58+
59+
LinkedList<String> result = new LinkedList<>();
60+
61+
Result.passwordCracker(passwords, loginAttempt, new HashSet<>(), result);
62+
63+
if (result.isEmpty()) {
64+
bufferedWriter.write("WRONG PASSWORD");
65+
} else {
66+
bufferedWriter.write(String.join(" ", result));
67+
}
68+
69+
bufferedWriter.newLine();
70+
} catch (IOException ex) {
71+
throw new RuntimeException(ex);
72+
}
73+
});
74+
75+
bufferedReader.close();
76+
bufferedWriter.close();
77+
}
78+
}

0 commit comments

Comments
 (0)