[프로그래머스/Java] 옹알이(1)

Yujin·2025년 6월 18일

CodingTest

목록 보기
3/51

문제

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

문제 접근 방법

  1. 발음할 수 있는 단어들을 모은 배열을 만든다
  2. 반복문을 사용해서 babbling의 값들들 중 pass의 값을 포함하는 것이 있으면 "/" 로 replace
    -> 처음에는 그냥 ""로 replace를 하였는데, 그러면 남은 값들이 또 하나의 단어가 되어 pass의 값과 비교해 맞다고 체크하길래
    "/"로 바꾼 루 replaceAll을 사용해 모든 "/"를 ""로 replace를 한다.
  3. 처음에는 또다른 새로운 배열을 만들어 바뀐 단어를 넣어준 후 isEmpty를 사용하려 했는데,
    (GPT가 알려줌) 그냥 처음 반복문 안에서 b.isEmpty() answer ++ 를 사용하면 됐었다.

나의 코드

import java.util.*;

class Solution {
    public int solution(String[] babbling) {
        String[] pass = {"aya", "ye", "woo", "ma"}; 
        int answer = 0;

        for(String b : babbling){
            for(String p : pass){
                if(b.contains(p)){
                    b = b.replace(p,"/");   
                } 
            } 
            b = b.replaceAll("/", "");       
            if(b.isEmpty())
                answer ++;
        }
        return answer;
    }
}

개선 코드

import java.util.*;

class Solution {
    public int solution(String[] babbling) {
        int answer = 0;
				
        for(String b : babbling){
            b = b.replace("aya", "/");
            b = b.replace("ye", "/");
            b = b.replace("woo", "/");
            b = b.replace("ma", "/");
            
            b = b.replaceAll("/", "");       
            if(b.isEmpty())
                answer ++;
        }
        return answer;
    }
}

0개의 댓글