코딩테스트/프로그래머스

프로그래머스 옹알이 (2)

의현 2025. 7. 4. 17:16

링크 : https://school.programmers.co.kr/learn/courses/30/lessons/133499

문제 풀이

startsWith 메서드를 이용하여 접근 (사용 방법은 mdn 참고)

검사를 시작할 index를 증가시키면서 match가 되지 않았거나 while문이 종료되었을 경우 검사하려는 word의 길이와 index가 같다면 읽을 수 있는 단어이므로 answer 1증가

function solution(babbling) {
    var answer = 0;
    const tells = ['aya', 'ye', 'woo', 'ma'];
    
    for (let word of babbling) {
        let prev = '';
        let index = 0;
        let matched = false;
        
        while (index < word.length) {
            let matched = false;
            
            for (const tell of tells) {
                if (word.startsWith(tell, index) && tell !== prev) {
                    index += tell.length;
                    prev = tell;
                    matched = true;
                    break;
                }
            }
            
            if (!matched) break;
        }
        
        if (index === word.length) answer++;
    }
    
    return answer;
}

결론

replaceAll을 이용하여도 문제를 해결할 수 있음 (다른 사람 문제 풀이 참고)

문제의 핵심은 같은 단어로 연속으로 발음을 하지 못한 다는 것

따라서 일반적으로 repalceAll을 할 경우 'yeye'와 같은 단어도 허용이 되기 때문에 이러한 경우를 제외 해주면 쉽게 해결 가능

-> replaceAll('yeye', '*')와 같이 연속 발음을 처리하는 로직을 추가하면 됨