Skip to content

Commit 907ce69

Browse files
author
Gan Kai
committed
⚡ 1178
1 parent 896aef0 commit 907ce69

File tree

1 file changed

+77
-0
lines changed

1 file changed

+77
-0
lines changed

1178.猜字谜.js

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
/*
2+
* @lc app=leetcode.cn id=1178 lang=javascript
3+
*
4+
* [1178] 猜字谜
5+
*/
6+
7+
// @lc code=start
8+
/**
9+
* @param {string[]} words
10+
* @param {string[]} puzzles
11+
* @return {number[]}
12+
*/
13+
var findNumOfValidWords = function(words, puzzles) {
14+
const frequency = new Map();
15+
16+
for (const word of words) {
17+
let mask = 0;
18+
for (const ch of word) {
19+
mask |= (1 << (ch.charCodeAt() - 'a'.charCodeAt()));
20+
}
21+
if (CountOne(mask) <= 7) {
22+
frequency.set(mask, (frequency.get(mask) || 0) + 1);
23+
}
24+
}
25+
26+
const ans = [];
27+
for (const puzzle of puzzles) {
28+
let total = 0;
29+
30+
// 枚举子集方法一
31+
// for (let choose = 0; choose < (1 << 6); ++choose) {
32+
// let mask = 0;
33+
// for (let i = 0; i < 6; ++i) {
34+
// if (choose & (1 << i)) {
35+
// mask |= (1 << (puzzle[i + 1].charCodeAt() - 'a'.charCodeAt()));
36+
// }
37+
// }
38+
// mask |= (1 << (puzzle[0].charCodeAt() - 'a'.charCodeAt()));
39+
// if (frequency.has(mask)) {
40+
// total += frequency.get(mask);
41+
// }
42+
// }
43+
// 枚举子集方法二
44+
let mask = 0;
45+
for (let i = 1; i < 7; ++i) {
46+
mask |= (1 << (puzzle[i].charCodeAt() - 'a'.charCodeAt()));
47+
}
48+
let subset = mask;
49+
while (subset) {
50+
let s = subset | (1 << (puzzle[0].charCodeAt() - 'a'.charCodeAt()));
51+
if (frequency.has(s)) {
52+
total += frequency.get(s);
53+
}
54+
subset = (subset - 1) & mask;
55+
}
56+
// 在枚举子集的过程中,要么会漏掉全集 mask,要么会漏掉空集
57+
// 这里会漏掉空集,因此需要额外判断空集
58+
if (frequency.has(1 << (puzzle[0].charCodeAt() - 'a'.charCodeAt()))) {
59+
total += frequency.get(1 << (puzzle[0].charCodeAt() - 'a'.charCodeAt()));
60+
}
61+
ans.push(total);
62+
}
63+
return ans;
64+
};
65+
66+
function CountOne(n) {
67+
const str = n.toString(2);
68+
let count = 0;
69+
for (const ch of str) {
70+
if (parseInt(ch) === 1) {
71+
count++;
72+
}
73+
}
74+
return count;
75+
}
76+
// @lc code=end
77+

0 commit comments

Comments
 (0)