leetcode 1178. 猜字谜

题目要求

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

  • 单词 word 中包含谜面 puzzle 的第一个字母。
  • 单词 word 中的每一个字母都可以在谜面 puzzle 中找到。
    例如,如果字谜的谜面是 “abcdefg”,那么可以作为谜底的单词有 “faced”, “cabbage”, 和 “baggage”;而 “beefed”(不含字母 “a”)以及 “based”(其中的 “s” 没有出现在谜面中)都不能作为谜底。

返回一个答案数组 answer,数组中的每个元素 answer[i] 是在给出的单词列表 words 中可以作为字谜迷面 puzzles[i] 所对应的谜底的单词数目。

输入:
words = [“aaaa”,“asas”,“able”,“ability”,“actt”,“actor”,“access”],
puzzles = [“aboveyz”,“abrodyz”,“abslute”,“absoryz”,“actresz”,“gaswxyz”]
输出:[1,1,3,2,4,0]
解释:
1 个单词可以作为 “aboveyz” 的谜底 : “aaaa”
1 个单词可以作为 “abrodyz” 的谜底 : “aaaa”
3 个单词可以作为 “abslute” 的谜底 : “aaaa”, “asas”, “able”
2 个单词可以作为 “absoryz” 的谜底 : “aaaa”, “asas”
4 个单词可以作为 “actresz” 的谜底 : “aaaa”, “asas”, “actt”, “access”
没有单词可以作为 “gaswxyz” 的谜底,因为列表中的单词都不含字母 ‘g’。

代码

class Solution {
    
    
public:
    int CountOnes(int n){
    
      //count ones of binary number n
        int count=0;
        while(n){
    
    
            count++;
            n=n&(n-1);
        }
        return count;
    }

    vector<int> findNumOfValidWords(vector<string>& words, vector<string>& puzzles) {
    
    
        unordered_map<int,int> word_bitmap; //key:word->bitmask,value:number of occurrences
        int bitmask;
        for(string word:words){
    
    
            bitmask=0;
            for(char ch:word){
    
    
                bitmask|=1<<(ch-'a');
            }
            if(CountOnes(bitmask)<=7){
    
    
                word_bitmap[bitmask]++;
            }
        }

        vector<int> answer;
        int cnt;
        for(string puzzle:puzzles){
    
    
            bitmask=0,cnt=0;
            for(char ch:puzzle){
    
    
                bitmask|=1<<(ch-'a');
            }

            // check subsets of puzzle's bitmask and add up numbers of occurrences
            for(int subset=bitmask;subset;subset=(subset-1)&bitmask){
    
    
                if((subset&(1<<(puzzle[0]-'a')))&&word_bitmap.count(subset)){
    
    
                    cnt+=word_bitmap[subset];
                }
            }
            answer.push_back(cnt);
        }
        
        return answer;
    }
};

笔记

  1. 遍历map:for(auto &ite:map){ cout<<ite.first<<ite.second<<endl;}
  2. 枚举二进制子集:伪代码:for(int i=s; i ; i=(i-1)&s)
    主要意思:当i不为0时,i-1表示将i最后一位1及其后面全部取反,(i-1)&s表示去掉i最后一位1
  3. map和unordered_map:map是红黑树实现,较为有序。unordered_map是哈希表实现,当数据较多且查找次数多时,性能更加优秀。

猜你喜欢

转载自blog.csdn.net/livingsu/article/details/114198235