프로그래머스 연습문제 숫자 짝꿍 [JAVA] - 22년 10월 13일

Denia·2022년 10월 12일
2

코딩테스트 준비

목록 보기
95/201

StringBuilder를 사용하지 않고 그냥 String 끼리 합쳐서 문자열을 만들면 시간 초과가 발생한다.

StringBuilder 사용

class Solution {
    public String solution(String X, String Y) {
        StringBuilder answer = new StringBuilder();

        int[] arrX = new int[10];
        int[] arrY = new int[10];

        countNumInArr(X, arrX);
        countNumInArr(Y, arrY);

        for (int i = arrX.length - 1; i >= 0; i--) {
            while (arrX[i] >= 1 && arrY[i] >= 1) {
                arrX[i]--;
                arrY[i]--;

                answer.append(i);
            }
        }

        if (answer.toString().equals("")) {
            return "-1";
        } else if (answer.toString().startsWith("0")) {
            return "0";
        } else {
            return answer.toString();
        }
    }

    private void countNumInArr(String str, int[] arr) {
        for (int i = 0; i < str.length(); i++) {
            int index = str.charAt(i) - '0';

            arr[index]++;
        }
    }
}

String 사용

class Solution {
    public String solution(String X, String Y) {
        String answer = "";

        int[] arrX = new int[10];
        int[] arrY = new int[10];

        countNumInArr(X, arrX);
        countNumInArr(Y, arrY);

        for (int i = arrX.length - 1; i >= 0; i--) {
            while (arrX[i] >= 1 && arrY[i] >= 1) {
                arrX[i]--;
                arrY[i]--;

                answer += i;
            }
        }

        if (answer.equals("")) {
            return "-1";
        } else if (answer.startsWith("0")) {
            return "0";
        } else {
            return answer;
        }
    }

    private void countNumInArr(String str, int[] arr) {
        for (int i = 0; i < str.length(); i++) {
            int index = str.charAt(i) - '0';

            arr[index]++;
        }
    }
}

profile
HW -> FW -> Web

0개의 댓글