프로그래머스/Lv1

[프로그래머스/Javascript] Lv.1 옹알이

woo.oing 2026. 1. 27. 11:28

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

 

프로그래머스

SW개발자를 위한 평가, 교육의 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프

programmers.co.kr

 

 

✓ 풀이과정

 

1. 한 단어의 알파벳 하나씩 확인하면서 임시 변수(temp)에 추가 저장

2. 말할 수 있는 단어에 temp가 포함되어 있다면 연속으로 같은 단어를 방지하기 위해 before에 기억해두고 temp를 초기화

3. 한 단어의 모든 알파벳을 확인했을 때 temp에 남아있는 알파벳이 없을 때만 말할 수 있는 단어로 판단하여 개수 카운트

 

function solution(babbling) {
  let answer = 0;
  let canSayWord = ["aya", "ye", "woo", "ma"];

  for (const word of babbling) {
    let temp = [];
    let before = "";

    for (const char of word) {
      temp.push(char);

      let tempStr = temp.join("");
      if (tempStr !== before && canSayWord.includes(tempStr)) {
        before = tempStr;
        temp = [];
      }
    }

    if (!temp.length) answer++;
  }

  return answer;
}

 

위 코드도 정답을 통과하지만 temp을 배열로 생성하고 하나씩 push 하는 비용보다 문자열로 처리하는 방법이 더 효율적일 것 같아서 수정했습니다

 

 

 최종코드

function solution(babbling) {
  let answer = 0;
  let canSayWord = ["aya", "ye", "woo", "ma"];

  for (const word of babbling) {
    let temp = "";
    let before = "";

    for (const char of word) {
      temp += char;

      if (temp !== before && canSayWord.includes(temp)) {
        before = temp;
        temp = "";
      }
    }

    if (!temp.length) answer++;
  }

  return answer;
}