Leetcode 1684. Count the Number of Consistent Strings
1684. Count the Number of Consistent Strings
You are given a string allowed
consisting of distinct characters and an array of strings words
. A string is considered consistent if all characters in the string appear in the string allowed
.
Return the number of consistent strings in the array words
.
Example:
Input: allowed = "ab", words = ["ad","bd","aaab","baa","badab"]
Output: 2
Explanation: String "aaab" and "baa" are consistent since they only contain characters 'a' and 'b'.
allowed
unique?
allowed
consists of distinct characters.allowed
and words
?
allowed
and lengths of individual strings in words
can be various, but common problem constraints apply).words
contain empty strings?
set
or a vector<bool>
(size 26) to keep track of characters in allowed
for O(1) membership checking.allowed
characters to a set
or vector<bool>
.words
and verify if all its characters exist in the allowed
set/vector.words
is empty, return 0.#include <iostream>
#include <vector>
#include <string>
#include <unordered_set>
using namespace std;
class Solution {
public:
int countConsistentStrings(string allowed, vector<string>& words) {
unordered_set<char> allowedSet(allowed.begin(), allowed.end());
int consistentCount = 0;
for(const string& word : words) {
bool isConsistent = true;
for(char ch : word) {
if(allowedSet.find(ch) == allowedSet.end()) {
isConsistent = false;
break;
}
}
if(isConsistent) {
++consistentCount;
}
}
return consistentCount;
}
};
int main() {
Solution solution;
vector<string> words1 = {"ad","bd","aaab","baa","badab"};
string allowed1 = "ab";
cout << "The number of consistent strings: " << solution.countConsistentStrings(allowed1, words1) << endl; // Output: 2
vector<string> words2 = {"a","b","c","ab","ac","bc","abc"};
string allowed2 = "abc";
cout << "The number of consistent strings: " << solution.countConsistentStrings(allowed2, words2) << endl; // Output: 7
vector<string> words3 = {"cc","acd","b","ba","bac","bad","ac","d"};
string allowed3 = "cad";
cout << "The number of consistent strings: " << solution.countConsistentStrings(allowed3, words3) << endl; // Output: 4
return 0;
}
This implementation employs an unordered_set
to store the allowed characters and then checks each word against this set to determine consistency, hence counting the number of consistent strings as required.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?