매일 Algorithm

신재원·2023년 3월 6일
0

Algorithm

목록 보기
57/243

백준 12904번 (그리디)

import java.util.Scanner;

public class problem162 {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);


        String n = in.next();
        String m = in.next();
        /**
         입력
         n : B
         m : ABBB
         출력 : 1
         **/
        while (n.length() < m.length()) {
            StringBuilder sb = new StringBuilder();
            // 문자열의 뒤에서부터 검증을하여 입력된 문자 n이 될때까지한다.
            if (m.endsWith("A")) {
                m = m.substring(0, m.length() - 1);
            } else if (m.endsWith("B")) {
                m = m.substring(0, m.length() - 1);
                // reverse() 문자열을 뒤집는다.
                m = sb.append(m).reverse().toString();
            }
        }


        if (n.equals(m)) {
            System.out.print(1);
        } else {
            System.out.print(0);
        }
    }
}

백준 1417번 (그리디)

import java.util.Arrays;
import java.util.Comparator;
import java.util.Scanner;

public class problem163 {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);

        int size = in.nextInt();
        int d = in.nextInt();

        // 후보자가 혼자인경우
        if (size == 1) {
            System.out.print(0);
            return;
        }
        Integer[] arr = new Integer[size - 1];

        for (int i = 0; i < size - 1; i++) {
            arr[i] = in.nextInt();
        }

        int count = 0;

        while (true) {
            // 내림차순으로 while문이 탈출될때까지 정렬한다.
            Arrays.sort(arr, Comparator.reverseOrder());

            // while문 탈출 조건을 위해 boolean
            boolean flag = true;
            int max = arr[0]; // 후보를 찍을려고 하는 수 중 최대
            if (d <= max) {
                count++;
                d++;
                arr[0]--;
				// max값보다 d값이 커지게되면 flag는 true로 
                // 초기화 하였기때문에 while문을 탈출한다.
                flag = false; 
            }
            if (flag)
                break;
        }
        System.out.print(count);
    }
}

0개의 댓글