https://leetcode-cn.com/problems/number-of-valid-words-for-each-puzzle/
思路:看完题目会发现关键点是一个单词中出现的字符种类,和个数没有关系,那么我们可以用位运算表示某个单词含有的字符种类。具体做法是,如果它含有小写字母 x x x,我们就可以把它二进制表示的第 x − ′ a ′ x-'a' x−′a′位置为 1 1 1。这样就将字符串变成了整数,接下来构建一个哈希表,记录某个整数所对应的字符串个数。对于每个 p u z z l e puzzle puzzle我们可以得到它的哈希值,接下来就是枚举它的所有子集,将对应的字符串个数累加起来即可。
class Solution {
public:
vector<int> findNumOfValidWords(vector<string>& words, vector<string>& puzzles) {
unordered_map<int,int> m;
int strHashVal=0;
for(const string &s : words)
{
strHashVal=0;
for(char c : s)
strHashVal|=1<<(c-'a');
if(__builtin_popcount(strHashVal)<=7)
++m[strHashVal];
}
int subset=0,n=puzzles.size(),cnt=0;
auto mend=m.end();
vector<int> ans(n);
int i=0;
for(const string &s : puzzles)
{
strHashVal=cnt=0;
for(int j=1;j<7;j++)
strHashVal|=1<<(s[j]-'a');
subset=strHashVal;
do
{
int tmp=subset | (1<<(s[0]-'a'));
auto it=m.find(tmp);
if(it!=mend)
cnt+=it->second;
subset=(subset-1)&strHashVal;
}while(subset!=strHashVal);
ans[i++]=cnt;
}
return ans;
}
};