본문 바로가기

verdantjuly/코딩테스트

프로그래머스 코딩테스트 연습 : 숫자 짝꿍 (20240315, java)

728x90

문제 바로가기: https://school.programmers.co.kr/learn/courses/30/lessons/131128

나의 풀이 FAIL

import java.util.*;

class Solution {
    public String solution(String X, String Y) {
        List<String> XList = new ArrayList<>(Arrays.asList(X.split("")));
        List<String> YList = new ArrayList<>(Arrays.asList(Y.split("")));
        List<String> resultArray = new ArrayList();
        for(int i =0; i<YList.size(); i++){
            if(XList.contains(YList.get(i))){
                XList.remove(XList.indexOf(YList.get(i)));
                resultArray.add(YList.get(i));
            }
        }
        Collections.sort(resultArray, Collections.reverseOrder());
        String answer = String.join("",resultArray);

        
        if (answer == ""){
            return "-1";
        } else if (String.valueOf(answer.charAt(0)) == "0"){
            return "0";
        }
        return answer;
        
    }
}

 

다른 사람의 풀이

import java.util.*;

class Solution {
    public String solution(String X, String Y) {
        StringBuilder sb = new StringBuilder();
        PriorityQueue<Integer> pq1 = new PriorityQueue<>(Collections.reverseOrder());
        PriorityQueue<Integer> pq2 = new PriorityQueue<>(Collections.reverseOrder());

        for (int i=0; i<X.length(); i++) {
            pq1.offer(X.charAt(i) - '0');
        }
        for (int i=0; i<Y.length(); i++) {
            pq2.offer(Y.charAt(i) - '0');
        }

        while (!pq1.isEmpty() && !pq2.isEmpty()) {
            if (pq1.peek() == pq2.peek()) {
                sb.append(String.valueOf(pq1.poll()));
                pq2.poll();
            } else if (pq1.peek() > pq2.peek()) {
                pq1.poll();
            } else {
                pq2.poll();
            }
        }

        return sb.toString().equals("") ? "-1" : sb.toString().charAt(0)=='0' ? "0" : sb.toString();
    }
}

 

소감