leetcode1178。ワードパズル

主題の要件

アナグラムのパズルは文字列の形で与えられます。単語が次の2つの条件を満たす場合、それは答えとして数えられます。

  • 単語wordには、パズルの最初の文字が含まれています。
  • 単語wordのすべての文字はパズルで見つけることができます。
    たとえば、アナグラムの顔が「abcdefg」の場合、答えとして使用できる単語は「faced」、「cabbage」、「baggage」ですが、「beefed」(文字「a」なし)です。そして、「ベース」(その中で「S」はミステリーに表示されません)はミステリーへの答えとして使用できません。

回答配列answerを返します。配列answer [i]の各要素は、指定された単語リストの単語のパズル[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語は「絶対」として使用できます答え:「aaaa」、「asas」、「able」
2語は「absoryz」として使用できます答え:「aaaa」、「asas」
4語はOK「actresz」への回答として:「aaaa」、「asas」、「actt」、「access」
リスト内の単語には文字「g」が含まれていないため、「gaswxyz」への回答として使用できる単語はありません。 '。

コード

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