Leetcode 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 consistent if all characters in the string appear in the string allowed
.
Return the number of consistent strings in the array words
.
allowed = "ab"
, words = ["ad","bd","aaab","baa","badab"]
2
allowed = "abc"
, words = ["a","b","c","ab","ac","bc","abc"]
7
allowed = "cad"
, words = ["cc","acd","b","ba","bac","bad","ac","d"]
4
allowed
string be empty?
allowed
string consists of distinct characters, so it cannot be empty.allowed
and words
?
allowed
is in the range [1, 26]
.words
is in the range [1, 10^4]
.words
is in the range [1, 10^4]
.words[i]
and allowed
consist of only lowercase English letters.allowed
Characters:
allowed
string into a set of characters for faster lookup.words
, check if all characters are in the allowed
set.allowed
set.import java.util.HashSet;
import java.util.Set;
public class Solution {
public int countConsistentStrings(String allowed, String[] words) {
// Convert the allowed string into a set for fast lookup
Set<Character> allowedSet = new HashSet<>();
for (char ch : allowed.toCharArray()) {
allowedSet.add(ch);
}
int count = 0; // Initialize the counter for consistent strings
// Iterate through each word in the array
for (String word : words) {
boolean isConsistent = true;
for (char ch : word.toCharArray()) {
if (!allowedSet.contains(ch)) {
isConsistent = false;
break;
}
}
if (isConsistent) {
count++;
}
}
return count; // Return the number of consistent strings
}
public static void main(String[] args) {
Solution sol = new Solution();
System.out.println(sol.countConsistentStrings("ab", new String[]{"ad","bd","aaab","baa","badab"})); // Output: 2
System.out.println(sol.countConsistentStrings("abc", new String[]{"a","b","c","ab","ac","bc","abc"})); // Output: 7
System.out.println(sol.countConsistentStrings("cad", new String[]{"cc","acd","b","ba","bac","bad","ac","d"})); // Output: 4
}
}
allowed
to a Set: O(n), where n
is the length of the allowed
string.m
is the number of words and k
is the average length of a word in words
.Overall, the time complexity is O(n + m*k), which is efficient given the problem constraints.
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?