주어진 문자열 allowed와 문자열 배열 words가 있습니다. allowed 문자열은 서로 다른 문자들로 이루어져 있습니다.
각 words 배열의 문자열이 allowed에 있는 문자들만 포함하고 있을 때, 그 문자열을 "일관된 문자열"이라고 합니다.
여러분의 목표는 words 배열에서 일관된 문자열의 개수를 세는 것입니다.
입력 : allowed = "ab" , words = ["ad", "bd", "aaab", "baa", "badab"]
출력 : 2설명 : "aaab"와 "baa"가 일관된 문자열입니다. 이들은 'a'와 'b'만 포함하고 있습니다.
입력 : allowed = "abc" , words = ["a", "b", "c", "ab", "ac", "bc", "abc"]
출력 : 7설명 : 모든 문자열이 일관된 문자열입니다. 모두 'a', 'b', 'c'로만 구성되어 있습니다.
입력 :allowed = "cad", words = ["cc", "acd", "b", "ba", "bac", "bad", "ac", "d"]
출력 : 4설명 : "cc", "acd", "ac", "d"가 일관된 문자열입니다.
function countConsistentStrings(allowed, words) {
// 허용된 문자들을 set으로 만들어 빠른 검색이 가능하게 만든다
const allowedSet = new Set(allowed);
let count = 0;
// words 배열의 각 문자열을 확인
for (let word of words) {
// 문자열의 모든 문자가 allowedSet에 포함되어 있는지 확인
if (word.split('').every(char => allowedSet.has(char))) {
count += 1;
}
}
return count;
function countConsistentStrings(allowed, words) {
const allowedSet = new Set(allowed);
return words.filter(word => [...word].every(char => allowedSet.has(char))).length;
}
function testCountConsistentStrings() {
function runTestCase(allowed, words, expected) {
const result = countConsistentStrings(allowed, words);
const passed = result === expected;
console.log(`allowed: "${allowed}", words: ${JSON.stringify(words)}, expected: ${expected}, got: ${result} - ${passed ? 'PASSED' : 'FAILED'}`);
}