[백준 1759 파이썬, 자바] 암호 만들기

일단 해볼게·2023년 3월 21일
0

백준

목록 보기
108/132

https://www.acmicpc.net/problem/1759

python (combination)

from itertools import combinations
 
L, C = map(int,input().split())
alpha = sorted(input().split()) # 알파벳 순으로 정렬
words = combinations(alpha, L)
 
for word in words:
    cnt_vow = 0

    for i in word: # 모음 있는지 검사
        if i in "aeiou":
            cnt_vow += 1
 
    if cnt_vow >= 1 and L - cnt_vow >= 2: # 전체 길이 - 모음 개수가 2 이상이면 자음의 개수가 2개 이상
        print(''.join(word))
  • 정렬 후 조합을 만들면 알파벳 순으로 만들어진다.
  • 자음의 개수 = 전체 길이 - 모음의 개수

java (DFS)

import java.util.*;
import java.io.*;
public class Main {

    static char[] arr;
    static int[] check;
    static int l, c;

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        StringTokenizer st = new StringTokenizer(br.readLine());

        l = Integer.parseInt(st.nextToken());
        c = Integer.parseInt(st.nextToken());
        arr = new char[c];
        check = new int[c];

        st = new StringTokenizer(br.readLine());

        for (int i = 0; st.hasMoreTokens(); i++) { // 한 줄로 된 입력값 넣기
            arr[i] = st.nextToken().charAt(0);
        }

        Arrays.sort(arr); // 정렬

        dfs(0, 0);

        br.close();
    }

    public static void dfs(int level, int length) {
        if(length == l) {
            StringBuilder sb = new StringBuilder();
            int vowel = 0; // 모음
            int consonant = 0; // 자음

            for (int i = 0 ; i < c; i++) {
                if (check[i] == 1) {
                    if (isVowel(arr[i])) { // 모음 판별
                        vowel++;
                    } else { // 자음일 때
                        consonant++;
                    }

                    sb.append(arr[i]);
                }
            }

            if (vowel >= 1 && consonant >= 2) { // 모음 1개, 자음 2개 이상
                System.out.println(sb);
            }

        } else {
            for (int i = level; i < c; i++) {
                check[i] = 1;
                dfs(i+1, length+1);
                check[i] = 0;
            }
        }
    }

    public static boolean isVowel(char c) {
        if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') {
            return true;
        } else {
            return false;
        }
    }

}
profile
시도하고 More Do하는 백엔드 개발자입니다.

0개의 댓글