2021-02-26 猜字谜

题目:
外国友人仿照中国字谜设计了一个英文版猜字谜小游戏,请你来猜猜看吧。

字谜的迷面 puzzle 按字符串形式给出,如果一个单词 word 符合下面两个条件,那么它就可以算作谜底:

单词 word 中包含谜面 puzzle 的第一个字母。
单词 word 中的每一个字母都可以在谜面 puzzle 中找到。
例如,如果字谜的谜面是 “abcdefg”,那么可以作为谜底的单词有 “faced”, “cabbage”, 和 “baggage”;而 “beefed”(不含字母 “a”)以及 “based”(其中的 “s” 没有出现在谜面中)。
返回一个答案数组 answer,数组中的每个元素 answer[i] 是在给出的单词列表 words 中可以作为字谜迷面 puzzles[i] 所对应的谜底的单词数目。
在这里插入图片描述
代码:

class Solution {
public:
    vector<int> findNumOfValidWords(vector<string>& words, vector<string>& puzzles) {
        unordered_map<int, int> count;
        
        for (auto &w : words) {
            int u = 0;
            for (auto c : w) {
                u |= 1 << (c - 'a');
            }
            ++count[u];
        }
        
        int n = puzzles.size();
        vector<int> ans(n);
        
        for (int i = 0; i < n; ++i) {
            string &w = puzzles[i]; // length = 7, 128
            
            int u = 0;
            for (auto c : w) {
                u |= 1 << (c - 'a');
            }
            
            for (int s = u; s; --s &= u) { // 枚举子集
                if (s & (1 << (w[0] - 'a')) && count.count(s)) {
                    ans[i] += count[s];
                } 
            }
        }
        
        return ans;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值