許可されているさまざまな文字の文字列と文字列配列の単語を指定します。文字列のすべての文字が許可されている場合、その文字列は一貫性のある文字列であると言われます。
単語配列内の一貫性のある文字列の数を返してください。
1 <= words.length <= 104
1 <= allowed.length <= 26
1 <= words [i] .length <= 10allowed
の文字が異なります。
words [i]は、小文字の英字のみを含めることができます。
方法1:許可をハッシュテーブルに入れる:
class Solution {
public:
int countConsistentStrings(string allowed, vector<string>& words) {
vector<bool> allowedList(256, false);
for (char c : allowed) {
allowedList[c] = true;
}
unsigned consistentStringNum = 0;
for (string &s : words) {
size_t i = 0;
for ( ; i < words.size(); ++i) {
if (!allowedList[s[i]]) {
break;
}
}
if (i == s.size()) {
++consistentStringNum;
}
}
return consistentStringNum;
}
};
方法2:許可されたハッシュをintに格納してから、各単語の単語をハッシュします。原則は次の方法と同じです。
class Solution {
public:
int Biterization(string &s) {
int res = 0;
for (char c : s) {
res |= (1 << c - 'a');
}
return res;
}
int countConsistentStrings(string allowed, vector<string>& words) {
int allowBit = Biterization(allowed);
unsigned consistentStringNum = 0;
for (string &s : words) {
int sBit = Biterization(s);
if ((sBit | allowBit) == allowBit) {
++consistentStringNum;
}
}
return consistentStringNum;
}
};