【哈希】直接用HashSet,但是HashSet初始容量为16涉及到了扩容,所以效率略低一点。
class Solution {
// 9:40
Set<Character> set = new HashSet();
boolean check(String w) {
for (int i = 0; i < w.length(); i++) if (!set.contains(w.charAt(i))) return false;
return true;
}
public int countConsistentStrings(String allowed, String[] words) {
int ans = 0;
for (int i = 0; i < allowed.length(); i++) set.add(allowed.charAt(i));
for (var w: words) if (check(w)) ans++;
return ans;
}
}
【哈希】因为字母只有26个,所以可以用一个定长的数组来代替哈希表。
class Solution {
// 10:05
boolean[] set = new boolean[26];
boolean check(String w) {
for (int i = 0; i < w.length(); i++) {
if (!set[w.charAt(i) - 'a']) return false;
}
return true;
}
public int countConsistentStrings(String allowed, String[] words) {
for (int i = 0; i < allowed.length(); i++) set[allowed.charAt(i) - 'a'] = true;
int ans = 0;
for (String w: words) if (check(w)) ans++;
return ans;
}
}
【位运算】又是因为字母只有26个,所以可以用一个int的后面26位来保存这个信息。将原来的字符串编码,然后将两个编码后的哈希值进行或运算,如果跟之前的哈希值相同,说明没有引入新的位,也就是没有新出现的字母。
class Solution {
int mask(String w) {
int m = 0;
for (int i = 0; i < w.length(); i++) m |= 1 << (w.charAt(i) - 'a');
return m;
}
public int countConsistentStrings(String allowed, String[] words) {
int m = mask(allowed);
int ans = 0;
for (var w: words) if ((m | mask(w)) == m) ans++;
return ans;
}
}
class Solution {
public:
// 10:20
int mask(string s) {
int m = 0;
for (int i = 0; i < s.length(); i++) m |= 1 << (s[i] - 'a');
return m;
}
int countConsistentStrings(string allowed, vector<string>& words) {
int m = mask(allowed);
int ans = 0;
for (auto w: words) if ((m | mask(w)) == m) ans++;
return ans;
}
};