用哈希表可以完成时间复杂度为O(mn)的解法,官解给的是用位运算的解法,时间复杂度可以优化为 O ( n + ∑ m i ) O(n+∑m_i) O(n+∑mi)

class Solution {
public int countConsistentStrings(String allowed, String[] words) {
int res=0,mask=0;
//计算mask
for(int i=0;i<allowed.length();i++){
char ch=allowed.charAt(i);
mask|=1<<(ch-'a');
}
for(String word:words){
int mask1=0;
//计算mask1
for(int j=0;j<word.length();j++){
char ch=word.charAt(j);
mask1|=1<<(ch-'a');
}
//并集为mask,则说明为一致字符串
if((mask1|mask)==mask)
res++;
}
return res;
}
}
时间复杂度: O ( n + ∑ m i ) O(n+∑m_i) O(n+∑mi)
空间复杂度: O ( 1 ) O(1) O(1)