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

KIMYEONGJUN·3일 전
post-thumbnail

문제

내가 생각했을때 문제에서 원하는부분

머쓱이는 태어난 지 6개월 된 조카를 돌보고 있습니다.
조카는 아직 "aya", "ye", "woo", "ma" 네 가지 발음을 최대 한 번씩 사용해 조합한(이어 붙인) 발음밖에 하지 못합니다.
문자열 배열 babbling이 매개변수로 주어질 때, 머쓱이의 조카가 발음할 수 있는 단어의 개수를 return하도록 solution 함수를 완성해주세요.

내가 이 문제를 보고 생각해본 부분

solution 메서드는 문자열 배열 babbling을 입력받아 유효한 발음 단어 개수를 반환한다.
먼저, 검사할 음절들을 sounds 배열에 "aya", "ye", "woo", "ma"로 정의한다.
정규표현식 ^(aya|ye|woo|ma)+$을 컴파일하여 pattern에 저장한다.
이 패턴은 입력 문자열 전체가 이 네 가지 음절 조합으로만 이루어졌는지를 검사한다.
입력 배열 babbling의 각 단어에 대해 다음 절차를 수행한다.
pattern.matcher(word)로 단어가 패턴에 완전히 부합하는지 확인한다. 부합하지 않으면 건너뛴다.
패턴에 맞으면 각 음절에 대해 문자열 내 등장 횟수를 직접 센다.
while 루프를 돌면서 해당 음절의 위치를 찾아 등장 횟수를 누적하는데, 중복 사용 여부를 판단하기 위함이다.
만약 한 음절이 2번 이상 등장하면 유효하지 않은 단어로 간주하고 검사 종료한다.
모든 음절이 중복 없이 최대 한 번씩만 등장하면 answer를 1 증가시킨다.
최종적으로 answer를 반환한다.
main 메서드에서는 테스트 케이스 두 개를 입력하고, solution을 통해 나온 결과를 출력한다.

코드로 구현

import java.util.regex.Pattern;
import java.util.regex.Matcher;

class Solution {
    public int solution(String[] babbling) {
        int answer = 0;
        String[] sounds = {"aya", "ye", "woo", "ma"};
        Pattern pattern = Pattern.compile("^(aya|ye|woo|ma)+$");

        for (String word : babbling) {
            Matcher matcher = pattern.matcher(word);
            if (!matcher.matches()) {
                continue;
            }

            boolean valid = true;
            for (String sound : sounds) {
                int count = 0;
                int index = 0;
                while ((index = word.indexOf(sound, index)) != -1) {
                    count++;
                    index += sound.length();
                    if (count > 1) {
                        valid = false;
                        break;
                    }
                }
                if (!valid) break;
            }

            if (valid) answer++;
        }

        return answer;
    }
}

프로그래머스 코드

package programmers.programmers2;

import java.util.regex.Pattern;
import java.util.regex.Matcher;

// 프로그래머스 옹알이 (1)
public class Main117 {
    public static void main(String[] args) {
        String[] babbling1 = {"aya", "yee", "u", "maa", "wyeoo"};
        String[] babbling2 = {"ayaye", "uuuma", "ye", "yemawoo", "ayaa"};

        // 결과 출력
        System.out.println(solution(babbling1)); // 1
        System.out.println(solution(babbling2)); // 3
    }

    public static int solution(String[] babbling) {
        int answer = 0;
        String[] sounds = {"aya", "ye", "woo", "ma"};
        Pattern pattern = Pattern.compile("^(aya|ye|woo|ma)+$");

        for (String word : babbling) {
            Matcher matcher = pattern.matcher(word);
            if (!matcher.matches()) {
                continue;
            }

            boolean valid = true;
            for (String sound : sounds) {
                int count = 0;
                int index = 0;
                while ((index = word.indexOf(sound, index)) != -1) {
                    count++;
                    index += sound.length();
                    if (count > 1) {
                        valid = false;
                        break;
                    }
                }
                if (!valid) break;
            }

            if (valid) answer++;
        }

        return answer;
    }
}

위에 있는 코드를 변경한 코드

마무리

코드와 설명이 부족할수 있습니다. 코드를 보시고 문제가 있거나 코드 개선이 필요한 부분이 있다면 댓글로 말해주시면 감사한 마음으로 참고해 코드를 수정 하겠습니다.

profile
Junior backend developer

0개의 댓글