-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathCountTheNumberOfConsistentStrings.js
67 lines (56 loc) · 1.42 KB
/
CountTheNumberOfConsistentStrings.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
// Solution with Arrays
/**
* @param {string} allowed
* @param {string[]} words
* @return {number}
*/
var countConsistentStrings = function(allowed, words) {
const charArr = new Array(26).fill(0);
let freq = 0;
for(let ch of allowed) {
charArr[ch.charCodeAt(0) - 'a'.charCodeAt(0)]++;
}
words.forEach((word) => {
let isConsistent = true;
for(let ch of word) {
if(!charArr[ch.charCodeAt(0) - 'a'.charCodeAt(0)] > 0) isConsistent = false;
}
if(isConsistent) freq++;
});
return freq;
};
// Solution with Set
/**
* @param {string} allowed
* @param {string[]} words
* @return {number}
*/
var countConsistentStrings = function(allowed, words) {
const allowedSet = new Set(allowed);
let consistentCount = 0;
for (let word of words) {
let isConsistent = true;
for (let char of word) {
if (!allowedSet.has(char)) {
isConsistent = false;
break;
}
}
if (isConsistent) {
consistentCount++;
}
}
return consistentCount;
};
// Set Solution - JS Brute Force
/**
* @param {string} allowed
* @param {string[]} words
* @return {number}
*/
var countConsistentStrings = function(allowed, words) {
const allowedSet = new Set(allowed);
return words.filter(word =>
[...word].every(char => allowedSet.has(char))
).length;
};