-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCrib.java
More file actions
83 lines (77 loc) · 2.45 KB
/
Crib.java
File metadata and controls
83 lines (77 loc) · 2.45 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
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.HashMap;
public class Crib {
public static Trie trie;
public static void main(String[] args){
try(BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))){
String init = reader.readLine();
int n = Integer.parseInt(reader.readLine());
trie = new Trie();
for (int i = 0; i < n; i++) {
trie.insert(reader.readLine());
}
if(check(init)){
System.out.println("YES");
} else {
System.out.println("NO");
}
} catch (Exception ex){
System.out.println(ex.getMessage());
}
}
public static boolean check(String init){
char[] letters = init.toCharArray();
boolean[] dp = new boolean[letters.length + 1];
dp[0] = true;
for (int i = 1; i <= letters.length; i++) {
if(dp[i - 1]){
TrieNode current = trie.getRoot();
for (int j = i; j <= letters.length ; j++) {
char letter = letters[j - 1];
current = current.getChildren().get(letter);
if(current != null){
if(current.isWord()) {
dp[j] = true;
}
} else {
break;
}
}
}
}
return dp[letters.length];
}
public static class Trie {
private TrieNode root;
public Trie(){
root = new TrieNode();
}
public void insert(String word){
TrieNode current = root;
for(char letter: word.toCharArray()){
current = current.getChildren().computeIfAbsent(letter, t -> new TrieNode());
}
current.setWord(true);
}
public TrieNode getRoot() {
return root;
}
}
public static class TrieNode {
private HashMap<Character, TrieNode> children;
private boolean isWord;
public TrieNode(){
children = new HashMap<>();
}
public HashMap<Character, TrieNode> getChildren() {
return children;
}
public boolean isWord() {
return isWord;
}
public void setWord(boolean word) {
isWord = word;
}
}
}