백준 - 비밀번호 발음하기 / Silver 5 / 4659번 / Java

Young Hun Park·2023년 2월 13일
0

문제 📋

백준 - 비밀번호 발음하기

풀이 📝

package BaekJoon;

import java.io.*;
import java.util.*;

public class PronouncePassword_4659 {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));

        List<String> passwords = new ArrayList<>();

        while (true) {
            String password = br.readLine();

            if (password.equals("end")) {
                break;
            }
            passwords.add(password);
        }

        for (String password : passwords) {
            String answer = solution(password);
            bw.write("<" + password + ">" + " is " + answer + "\n");
        }
        bw.flush();
    }

    public static String solution(String password) {
        char[] vowels = {'a', 'e', 'i', 'o', 'u'};

        boolean hasVowel = false;
        boolean isSameLetter = false;

        int vowelCnt = 0;
        int consonantCnt = 0;

        String answer = "acceptable.";

        for (int i=0; i<password.length(); i++) {
            boolean isVowel = false;
            char letter = password.charAt(i);

            if (i>0) {
                if (letter == password.charAt(i-1) && letter != 'e' && letter != 'o') {
                    isSameLetter = true;
                    break;
                }
            }

            for (char vowel : vowels) {
                if (letter == vowel) {
                    hasVowel = true;
                    isVowel = true;
                    vowelCnt ++;
                    consonantCnt = 0;
                    break;
                }
            }

            if (!isVowel) {
                vowelCnt = 0;
                consonantCnt ++;
            }

            if (vowelCnt > 2 || consonantCnt > 2) break;
        }
        if (!hasVowel || vowelCnt > 2 || consonantCnt > 2 || isSameLetter) {
            answer = "not " + answer;
        }

        return answer;
    }
}

품질이 좋은 비밀번호를 찾아내는 문제로 다음과 같은 3가지 조건을 만족해야한다.

1. 모음(a,e,i,o,u) 하나를 반드시 포함하여야 한다.
2. 모음이 3개 혹은 자음이 3개 연속으로 오면 안 된다.
3. 같은 글자가 연속적으로 두번 오면 안되나, ee 와 oo는 허용한다.

먼저 password를 하나씩 solution 함수에 인자로 받았다.
그런 다음 password를 문자 하나씩 순회하면서 먼저 3번째 조건을 체크해주었다.

이 후에는 현재 글자가 모음인지를 체크해서 모음이라면
hasVowel = true로 바꿔주고 vowelCnt를 +1 해주고
consonantCnt를 0으로 초기화 해주었다.

만약 자음이라면 consonantCnt를 +1 해주고 vowelCnt = 0으로 초기화 해주었다.

추가적으로 입력을 받고 출력하는 부분은 main함수에서 처리하고 로직은 solution 함수에만 넣음으로써 로직에만 집중할 수 있었다.

profile
개발자에게 유용한 지식

0개의 댓글