forked from Sunchit/Coding-Decoded
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNumberOfValidWordsForEachPuzzle.java
48 lines (44 loc) · 1.02 KB
/
NumberOfValidWordsForEachPuzzle.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
class Solution {
public List<Integer> findNumOfValidWords(String[] words, String[] puzzles) {
// English Character
Map<Integer, List<Integer>> bucket = new HashMap<>();
for (int i = 0; i < 26; i++) {
bucket.put(i, new ArrayList<>());
}
for (String word : words) {
int temp = getBitMask(word);
//
for (int i = 0; i < 26; i++) {
if ((temp & (1 << i)) != 0) {
bucket.get(i).add(temp);
}
}
}
List<Integer> res = new ArrayList<>();
for (String p : puzzles) {
int puzzleMask = getBitMask(p);
int c = p.charAt(0) - 'a';
int count = 0;
// searching for those words that have first puzzle char
for (int wordMask : bucket.get(c)) {
if ((wordMask & puzzleMask) == wordMask) {
count++;
}
}
res.add(count);
}
return res;
}
private int getBitMask(String s) {
int mask = 0;
for (int i = 0; i < s.length(); ++i) {
char c = s.charAt(i);
mask |= getBitMask(c);
}
return mask;
}
private int getBitMask(char c) {
int bit = (c - 'a');
return (1 << bit);
}
}