1.문제
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.
영단어가 들어있는 배열 words 가 주어질 때 words 단어들 중 allow 단어를 이루는 철자로만 이루어진 단어의 갯수를 리턴하는 문제이다.
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 <= 10^4
- 1 <= allowed.length <= 26
- 1 <= words[i].length <= 10
- The characters in allowed are distinct.
- words[i] and allowed contain only lowercase English letters.
2.풀이
- words 배열을 순회하면서 word 의 철자를 체크한다.
- word의 철자들을 순회하면서 allow 단어의 철자로 이루어져있는지 체크한다.
/**
* @param {string} allowed
* @param {string[]} words
* @return {number}
*/
const countConsistentStrings = function (allowed, words) {
const allowedArray = allowed.split("");
let count = 0;
// words 배열의 단어들을 순회
for (let i = 0; i < words.length; i++) {
for (let j = 0; j < words[i].length; j++) {
// 각 word 중 allowedArray에 존재하지 않는 알파벳이 있다면 count ++;
if (!allowedArray.includes(words[i][j])) {
count++;
break;
}
}
}
return words.length - count; // 전체 단어 수에서 조건에 맞지 않는 단어 수를 빼서 리턴한다.
};
3.결과
