You are given a string allowed consisting of distinct characters and an array of strings words. A string is consistent if all characters in the string appear in the string allowed.
Return the number of consistent strings in the arraywords.
Input: allowed ="ab", words =["ad","bd","aaab","baa","badab"]Output: 2Explanation: Strings "aaab" and "baa" are consistent since they only contain characters 'a' and 'b'.
Example 2:
1
2
3
Input: allowed ="abc", words =["a","b","c","ab","ac","bc","abc"]Output: 7Explanation: All strings are consistent.
Example 3:
1
2
3
Input: allowed ="cad", words =["cc","acd","b","ba","bac","bad","ac","d"]Output: 4Explanation: Strings "cc","acd","ac", and "d" are consistent.
publicclassSolution {
// Function to count consistent stringspublicintcountConsistentStrings(String allowed, String[] words) {
// Convert allowed characters to a set for O(1) lookups HashSet<Character> allowedSet =new HashSet<>();
for (char ch : allowed.toCharArray()) {
allowedSet.add(ch);
}
// Check if a word is consistent with the allowed setint count = words.length; // let all words be consistentfor (String word : words) {
for (char ch : word.toCharArray()) {
if (!allowedSet.contains(ch)) {
count--;
break;
}
}
}
return count;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
classSolution:
defcountConsistentStrings(self, allowed: str, words: List[str]) -> int:
# Convert allowed characters to a set for O(1) lookups allowed_set = set(allowed)
defis_consistent(word):
# Check if each character in the word is in the allowed setfor ch in word:
if ch notin allowed_set:
returnFalsereturnTrue# Count consistent words consistent_count =0for word in words:
if is_consistent(word):
consistent_count +=1return consistent_count
publicclassSolution {
// Function to count consistent stringspublicintcountConsistentStrings(String allowed, String[] words) {
// Convert allowed characters to a set for O(1) lookupsint allowedMask = 0;
for (char ch : allowed.toCharArray()) {
allowedMask |= 1 << (ch -'a');
}
// Check if a word is consistent with the allowed setint count = words.length; // let all words be consistentfor (String word : words) {
for (char ch : word.toCharArray()) {
int charMask = 1 << (ch -'a');
if ((allowedMask & charMask) == 0) {
count--;
break;
}
}
}
return count;
}
}