To solve the problem 1684. Count the Number of Consistent Strings in JavaScript, we need to count how many strings from a given array consist only of characters from a given allowed set of characters.
Problem Statement:
You’re given a string allowed
that consists of distinct characters, and an array words
where each string in words
consists of only lowercase English letters. A string is consistent if all characters in the string appear in the string allowed
.
The task is to return the number of consistent strings in the array words
.
Example:
Input: allowed = "abc", words = ["a","b","c","ab","ac","bc","abc","abcd"]
Output: 7
Explanation: The consistent strings are "a", "b", "c", "ab", "ac", "bc", "abc".
The string "abcd" is not consistent because it contains the character 'd' which is not in `allowed`.
Approach:
- Convert
allowed
string to a set for O(1) lookup time. - Iterate over each word in the
words
array and check if all characters in that word exist in theallowed
set. - Count the words that are consistent.
Code Implementation:
function countConsistentStrings(allowed, words) {
// Convert the allowed string to a Set for O(1) lookups
const allowedSet = new Set(allowed);
let count = 0;
// Iterate over each word in the words array
for (let word of words) {
let isConsistent = true;
// Check if every character in the word is in the allowed set
for (let char of word) {
if (!allowedSet.has(char)) {
isConsistent = false;
break;
}
}
// If the word is consistent, increment the count
if (isConsistent) {
count++;
}
}
return count;
}
// Example usage
const allowed = "abc";
const words = ["a","b","c","ab","ac","bc","abc","abcd"];
console.log(countConsistentStrings(allowed, words)); // Output: 7
Explanation:
- We first convert the
allowed
string into a setallowedSet
to make it easy to check if each character of the words is inallowed
. - For each word, we check whether all its characters exist in
allowedSet
. - If a word is consistent, we increment the
count
variable. - Finally, the function returns the total count of consistent strings.
This solution has a time complexity of O(n * m), where n
is the number of words, and m
is the average length of the words, which is efficient enough for typical input sizes.