문제 설명

내용이 정수로 이루어진 문자열 s가 있습니다. 이때 문자열에 더 많이 포함된 순서대로 숫자를 출력하는 프로그램을 구현하세요.

출력할 때 각 숫자는 공백으로 구분하고, 문자열에 포함되지 않은 숫자도 0번 등장한 것으로 가정하여 0~9 숫자를 모두 출력하세요.


입력 형식

· s : 양의 정수가 담긴 문자열


출력 형식

· s에 포함된 횟수가 많은 순서대로 적힌 문자열 반환


제약 사항

· 1 <= s <= 100000


입출력 예시

· 입력

  · s = "221123"

· 출력 : "2 1 3 0 4 5 6 7 8 9"

· 설명 : 많이 나타난 순서대로 2, 1, 3을 출력하며, 나타난 횟수가 0번인 나머지 숫자들은 숫자가 작은 수부터 순서대로 출력한다.


작성 코드

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

class Solution231 {
    public String solution(String s) {

        int[] count = new int[10];

        for (int i = 0; i < s.length(); i++) {
            // String 클래스의 charAt(0) 메서드는 문자열에서 해당 인덱스의 문자를 반환
            // 문자를 숫자로 변환하기 위해 char에서 int 타입으로 변환하고 있음
            // 이를 위해 아스키 코드 값에 따라 숫자를 변환
            // 0은 48, 1은 49, ..., 9는 57
            int num = s.charAt(i) - '0'; // 해당 문자에서 숫자0(48)을 빼면
            // 문자가 나타내는 실제 숫자 값을 얻을 수 있음
            // 즉, 2는 50 -> 50-48 -> 2
            count[num]++;
        }

        // 카운트 한 숫자를 빈도순으로 정렬한다.
        List<Integer> list = new ArrayList<>();
        for (int i = 0; i <= 9; i++) {
            list.add(i);
        }
        System.out.println(list);
        // count 배열의 값을 기준으로 list를 내림차순으로 정렬
        // 즉
        Collections.sort(list, (a, b) -> count[b] - count[a]);

        // 출력 문자열을 생성한다.
        StringBuilder sb = new StringBuilder();
        for (int num : list) {
            if (count[num] > 0) {
                sb.append(num).append(' ');
            }
        }

        // 나머지 숫자 0~9 중에서 카운트되지 않은 숫자를 출력한다.
        for (int i = 0; i <= 9; i++) {
            if (count[i] == 0) {
                sb.append(i).append(' ');
            }
        }
        return sb.toString().trim(); // trim은 마지막에 추가된 공백문자 제거
    }

    public static void main(String[] args) {
        Solution231 st = new Solution231();
        String s = "221123";
        System.out.println(st.solution(s));
    }
}

 

정답 코드

import java.util.Arrays;
import java.util.stream.IntStream;

class Solution {
    public String solution(String s) {
        int[] counts = new int[10];
        for (char c: s.toCharArray()) {
            counts[(int)(c - '0')]++;
        }

        int[] order = IntStream.range(0, 10).toArray();
        for (int high = 1; high < counts.length; high++) {
            for (int low = 0; low < high; low++) {
                if (counts[low] < counts[high]) {
                    int temp = counts[low];
                    counts[low] = counts[high];
                    counts[high] = temp;

                    temp = order[low];
                    order[low] = order[high];
                    order[high] = temp;
                } else if (counts[low] == counts[high] &&
                        order[low] > order[high]) {
                    int temp = order[low];
                    order[low] = order[high];
                    order[high] = temp;
                }
            }
        }
        String[] orderString = Arrays.stream(order)
                .boxed()
                .map(x->x.toString())
                .toArray(String[]::new);
        return String.join(" ", orderString);
    }

    public static void main(String[] args) {
        Solution st = new Solution();
        String s = "221123";
        System.out.println(st.solution(s));
    }
}