-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmochasAlienDictionary.java
44 lines (29 loc) · 1.09 KB
/
mochasAlienDictionary.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
import java.util.*;
class mochasAlienDictionary{
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String s = scanner.nextLine();
int n = scanner.nextInt();
scanner.nextLine();
Set<String> dictionary = new HashSet<>();
for (int i = 0; i < n; i++) {
dictionary.add(scanner.nextLine());
}
boolean canSegment = canSegmentString(s, dictionary);
System.out.println(canSegment ? "true" : "false");
}
private static boolean canSegmentString(String s, Set<String> dictionary) {
int length = s.length();
boolean[] dp = new boolean[length + 1];
dp[0] = true;
for (int i = 1; i <= length; i++) {
for (int j = 0; j < i; j++) {
if (dp[j] && dictionary.contains(s.substring(j, i))) {
dp[i] = true;
break;
}
}
}
return dp[length];
}
}