본문 바로가기
알고리즘 & 자료구조/프로그래머스

숫자 짝궁

by 신재권 2022. 11. 13.
package programmers;

public class 숫자짝꿍 {

   public static String solution(String X, String Y) {
      int[] countX = new int[10];
      int[] countY = new int[10];

      getNumberCount(X, countX);
      getNumberCount(Y, countY);

      StringBuilder sb = new StringBuilder();
      for (int i = 0; i < 10; i++) {
         if (isNotZeroAndEquals(countX, countY, i)) {
            sb.append(i);
            countX[i]--;
            countY[i]--;
            i = -1;
         }
      }

      if (sb.length() == 0) {
         return "-1";
      }
      if (sb.toString().matches("0*")) {
         return "0";
      }
      return sb.reverse().toString();
   }

   private static boolean isNotZeroAndEquals(int[] countX, int[] countY, int idx) {
      return countX[idx] != 0 && countY[idx] != 0 && (countX[idx] >= countY[idx] || countX[idx] <= countY[idx]);
   }

   private static void getNumberCount(String s, int[] count) {
      for (int i = 0; i < s.length(); i++) {
         count[s.charAt(i) - '0']++;
      }
   }

   public static void main(String[] args) {
      System.out.println(solution("100", "2345"));
      System.out.println(solution("100", "203045"));
      System.out.println(solution("100", "123450"));
      System.out.println(solution("12321", "42531"));
      System.out.println(solution("5525", "1255"));
   }

}

'알고리즘 & 자료구조 > 프로그래머스' 카테고리의 다른 글

기지국 설치  (0) 2022.11.16
성격 유형 검사하기  (0) 2022.11.15
푸드 파이트 대회  (0) 2022.11.11
콜라 문제  (0) 2022.11.10
체육복  (0) 2022.11.09