숫자 짝꿍

Heeeoh·2023년 3월 18일
0

프로그래머스

목록 보기
11/26
post-thumbnail

🔍문제 분석

✔️ 출처

https://school.programmers.co.kr/learn/courses/30/lessons/131128

📖 문제


숫자로된 문자열을 꺼내서 조건에 맞는 수를 조합하여 가장 큰 수를 문자열로 리턴

🔅 문제풀이

각 인덱스가 해당 숫자이고 값이 해당 숫자의 개수이다.


class Solution {
    public String solution(String X, String Y) {
        String answer = "";
        int[] Xarr = new int[10];
        int[] Yarr = new int[10];
        int[] result = new int[10];
        int cnt = 0;
        StringBuilder sb = new StringBuilder();

        for(String s : X.split("")){
            Xarr[Integer.parseInt(s)]++;
        }

        for(String s : Y.split("")){
            Yarr[Integer.parseInt(s)]++;
        }

        for(int i = 0; i < result.length; i++) {
            if(Xarr[i] > 0 && Yarr[i] > 0){
                result[i] = Math.min(Xarr[i], Yarr[i]);
                cnt++;
            }
        }
        int sum = 0;
        for(int i = 9; i >= 0; i--){
            for(int j = 0; j < result[i]; j++){
                if(result[i] > 0){
                    sb.append(String.valueOf(i));
                    sum += i;
                }
            }
        }
        if(cnt == 0) return "-1";
        else if(cnt > 0 && sum == 0) return "0";

        return sb.toString();
    }
}

    

너무느리다... parseInt와 String.valueOf를 남발해서 그런가 값이 커지면 느리다..

🔅 다른 사람 풀이

class Solution {
    public String solution(String X, String Y) {
        StringBuilder answer = new StringBuilder();
        int[] x = {0,0,0,0,0,0,0,0,0,0};
        int[] y = {0,0,0,0,0,0,0,0,0,0};
        for(int i=0; i<X.length();i++){
           x[X.charAt(i)-48] += 1;
        }
        for(int i=0; i<Y.length();i++){
           y[Y.charAt(i)-48] += 1;
        }

        for(int i=9; i >= 0; i--){
            for(int j=0; j<Math.min(x[i],y[i]); j++){
                answer.append(i);
            }
        }
        if("".equals(answer.toString())){
           return "-1";
        }else if(answer.toString().charAt(0)==48){
           return "0";
        }else {
            return answer.toString();
        }
    }
}

❗ 오답노트 / 필요한 지식

  1. 아스키코드로 숫자를 구하는 법을 기본지식으로 가져가야겠다.
    2.Integer.parseInt, StringValueOf를 사용하지 않고도 코드를 짜보자
    3.StringBuilder는 빠르다.
profile
열심히 살자

0개의 댓글