TIL

Jony·2024년 5월 27일
0

[TIL]

목록 보기
29/46
post-thumbnail

알고리즘 타임어택

  • 문제: 일관된 문자열의 개수 세기

  • 문제 요구사항 (정의)

주어진 문자열 allowed와 문자열 배열 words가 있습니다. allowed 문자열은 서로 다른 문자들로 이루어져 있습니다.
각 words 배열의 문자열이 allowed에 있는 문자들만 포함하고 있을 때, 그 문자열을 "일관된 문자열"이라고 합니다.
여러분의 목표는 words 배열에서 일관된 문자열의 개수를 세는 것입니다.

  • 인풋 아웃풋 예시

  • 예제 1

입력 : allowed = "ab" , words = ["ad", "bd", "aaab", "baa", "badab"]
출력 : 2

설명 : "aaab"와 "baa"가 일관된 문자열입니다. 이들은 'a'와 'b'만 포함하고 있습니다.

  • 예제 2

입력 : allowed = "abc" , words = ["a", "b", "c", "ab", "ac", "bc", "abc"]
출력 : 7

설명 : 모든 문자열이 일관된 문자열입니다. 모두 'a', 'b', 'c'로만 구성되어 있습니다.

  • 예제 3

입력 :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'}`);
    }
profile
알면 알수록 모르는 코태계

0개의 댓글