forked from AnasImloul/Leetcode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCheck if Word Can Be Placed In Crossword.java
101 lines (81 loc) · 2.53 KB
/
Check if Word Can Be Placed In Crossword.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
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
// Runtime: 522 ms (Top 5.97%) | Memory: 200.3 MB (Top 5.41%)
class Solution {
public boolean placeWordInCrossword(char[][] board, String word) {
String curr = "";
Trie trie = new Trie();
// Insert all horizontal strings
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[0].length; j++) {
if (board[i][j] == '#') {
insertIntoTrie(trie, curr);
curr = "";
}
else {
curr += board[i][j];
}
}
insertIntoTrie(trie, curr);
curr = "";
}
// Insert all vertical strings
for (int i = 0; i < board[0].length; i++) {
for (int j = 0; j < board.length; j++) {
if (board[j][i] == '#') {
insertIntoTrie(trie, curr);
curr = "";
}
else {
curr += board[j][i];
}
}
insertIntoTrie(trie, curr);
curr = "";
}
return trie.isPresent(word);
}
// Insert string and reverse of string into the trie
private void insertIntoTrie(Trie trie, String s) {
trie.insert(s);
StringBuilder sb = new StringBuilder(s);
sb.reverse();
trie.insert(sb.toString());
}
class TrieNode {
Map<Character, TrieNode> children;
boolean isEnd;
TrieNode() {
children = new HashMap<>();
isEnd = false;
}
}
class Trie {
TrieNode root;
Trie() {
root = new TrieNode();
}
void insert(String s) {
TrieNode curr = root;
for (int i = 0; i < s.length(); i++)
{
char c = s.charAt(i);
if (!curr.children.containsKey(c)) {
curr.children.put(c, new TrieNode());
}
curr = curr.children.get(c);
}
curr.isEnd = true;
}
boolean isPresent(String key) {
TrieNode curr = root;
return helper(key, 0, root);
}
boolean helper(String key, int i, TrieNode curr) {
if (curr == null)
return false;
if (i == key.length())
return curr.isEnd;
char c = key.charAt(i);
return helper(key, i + 1, curr.children.get(c)) || helper(key, i + 1, curr.children.get(' '));
}
}
}