It’s an easy problem from leet code which consists in:
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.
For a simple and straight forward resolution you can iterate the words array and grab each character and compare if exists on allowed String:
class Solution {
public int countConsistentStrings(String allowed, String[] words) {
//create counter
int count = 0;
// iterate words array
for(int i=0;i<words.length;i++){
// create check for each word
boolean isAllowed = true;
for(int j=0;j<words[i].length();j++){
// check if character exist in the allowed string
if(allowed.indexOf(words[i].charAt(j))==-1){
isAllowed = false; // doesn't exist
break;
}
}
// isAllowed = true means that all characters were on allowed string
if(isAllowed) count++;
}
// return counter
return count;
}
}
Runtime: 15 ms, faster than 56.55% of Java online submissions for Count the Number of Consistent Strings.
Memory Usage: 43.8 MB, less than 99.35% of Java online submissions for Count the Number of Consistent Strings.
The first line is to create the counter, then iterate the words array, on each iteration check for each word char, in this case I’ve used indexOf but you could’ve used contains, would work as well, and if was not there isAllowed would be false.
On the discussions there is a nice alternative by rock that uses stream which states:
public int countConsistentStrings(String allowed, String[] words) {
return Arrays.stream(words)
.mapToInt(w -> w.chars()
.allMatch(c -> allowed.contains((char)c + "")) ? 1 : 0)
.sum();
}
Also there is another solution that uses bits manipulation but I believe that goes off the concept of easy problem, and deep dive in a more low level. Once I get a post related to bits and moving around and the relation with that with resolution and the why’s then I will add extra examples using bits maniputation.
That’s it! If there is anything thing else to discuss feel free to drop a comment, if I missed anything let me know so I can update accordingly.
Until next post! :)
Top comments (0)