直接一致する場合は、単語とパズルの両方を1回トラバースする必要があるため、時間計算量はO(N * M * len)であり、確実にタイムアウトします。
ここでは、単語内のすべての文字をパズルで見つける必要があるため、単語を圧縮して整数intにマップできます。範囲は、0〜2 ^ 26の累乗で、この文字列に含まれる文字をマークします。次に、単語の頻度をカウントするHashMap。
次に、パズルをトラバースします。各パズルは7桁であるため、繰り返し番号はなく、0桁目を使用する必要があるため、最初の桁からパズルの部分文字列を列挙し、ハッシュマップに移動して対応する単語を見つけます。 、あなたは最終的な答えを得ることができます。
class Solution {
public:
vector<int> findNumOfValidWords(vector<string>& words, vector<string>& puzzles) {
// 字符串状态压缩,将字符串word->二进制数组
unordered_map<int,int> hashmap;
vector<int> res;
for(auto const &word:words){
int mask = 0;
for(auto const &c:word){
mask |= 1<< (c - 'a');
}
hashmap[mask]++;
}
// puzzles的长度最长为7,第一位固定,子串共有2^6个状态。
for(auto const &p:puzzles){
int count = 0;
for(int i=0;i<1<<6;i++){
int mask = 0;
for(int j=0;j<6;j++){
if(i&(1<<j)){
mask |= (1 << (p[j + 1] - 'a'));
}
}
mask |= (1<<(p[0]-'a'));
count+=hashmap[mask];
}
res.push_back(count);
}
return res;
}
};