1684. Count the Number of Consistent Strings LeetCode Solution
In this guide, you will get 1684. Count the Number of Consistent Strings LeetCode Solution with the best time and space complexity. The solution to Count the Number of Consistent Strings problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.
Table of Contents
- Problem Statement
- Complexity Analysis
- Count the Number of Consistent Strings solution in C++
- Count the Number of Consistent Strings solution in Java
- Count the Number of Consistent Strings solution in Python
- Additional Resources
Problem Statement of 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.
Example 1:
Input: allowed = “ab”, words = [“ad”,”bd”,”aaab”,”baa”,”badab”]
Output: 2
Explanation: Strings “aaab” and “baa” are consistent since they only contain characters ‘a’ and ‘b’.
Example 2:
Input: allowed = “abc”, words = [“a”,”b”,”c”,”ab”,”ac”,”bc”,”abc”]
Output: 7
Explanation: All strings are consistent.
Example 3:
Input: allowed = “cad”, words = [“cc”,”acd”,”b”,”ba”,”bac”,”bad”,”ac”,”d”]
Output: 4
Explanation: Strings “cc”, “acd”, “ac”, and “d” are consistent.
Constraints:
1 <= words.length <= 104
1 <= allowed.length <= 26
1 <= words[i].length <= 10
The characters in allowed are distinct.
words[i] and allowed contain only lowercase English letters.
Complexity Analysis
- Time Complexity:
- Space Complexity:
1684. Count the Number of Consistent Strings LeetCode Solution in C++
class Solution {
public:
int countConsistentStrings(string allowed, vector<string>& words) {
return accumulate(words.begin(), words.end(), 0,
[&allowed](int subtotal, const string& word) {
return subtotal + ranges::all_of(word, [&allowed](char c) {
return allowed.find(c) != string::npos;
});
});
}
};
/* code provided by PROGIEZ */
1684. Count the Number of Consistent Strings LeetCode Solution in Java
class Solution {
public int countConsistentStrings(String allowed, String[] words) {
return (int) Arrays.stream(words)
.filter(word -> word.matches(String.format("[%s]*", allowed)))
.count();
}
}
// code provided by PROGIEZ
1684. Count the Number of Consistent Strings LeetCode Solution in Python
class Solution:
def countConsistentStrings(self, allowed: str, words: list[str]) -> int:
return sum(all(c in allowed for c in word)
for word in words)
# code by PROGIEZ
Additional Resources
- Explore all LeetCode problem solutions at Progiez here
- Explore all problems on LeetCode website here
Happy Coding! Keep following PROGIEZ for more updates and solutions.