给你一个由不同字符组成的字符串 allowed 和一个字符串数组 words 。如果一个字符串的每一个字符都在 allowed 中,就称这个字符串是 一致字符串 。
请你返回 words 数组中 一致字符串 的数目。
1 = words.length = 104
1 = allowed.length = 26
1 = words[i].length = 10
allowed 中的字符 互不相同 。
words[i] 和 allowed 只包含小写英文字母。
法一:将allowed放入哈希表:
class Solution {
public:
int countConsistentStrings(string allowed, vectorstring words) {
vectorbool 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;
}
};
法二:将allowed哈希存入一个int中,再将每个words中的词哈希,原理与法一相同:
class Solution {
public:
int Biterization(string s) {
int res = 0;
for (char c : s) {
res |= (1 c - 'a');
}
return res;
}
int countConsistentStrings(string allowed, vectorstring words) {
int allowBit = Biterization(allowed);
unsigned consistentStringNum = 0;
for (string s : words) {
int sBit = Biterization(s);
if ((sBit | allowBit) == allowBit) {
++consistentStringNum;
}
}
return consistentStringNum;
}
};