작성일 :

문제 링크

20977번 - JOI ソート

설명

문자열의 문자를 재배열해 J가 O와 I보다, O가 I보다 항상 앞에 오도록 만드는 문제입니다.


접근법

J, O, I의 개수를 세어 J를 모두 출력한 뒤 O, I 순서로 출력하면 조건을 만족합니다.
문자의 상대 순서만 중요하므로 개수만 세면 충분합니다.


Code

C#

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
using System;
using System.Text;

class Program {
  static void Main() {
    var n = int.Parse(Console.ReadLine()!);
    var s = Console.ReadLine()!;
    int j = 0, o = 0, iCnt = 0;

    foreach (var ch in s) {
      if (ch == 'J') j++;
      else if (ch == 'O') o++;
      else iCnt++;
    }

    var sb = new StringBuilder();
    sb.Append('J', j);
    sb.Append('O', o);
    sb.Append('I', iCnt);
    Console.Write(sb);
  }
}

C++

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <bits/stdc++.h>
using namespace std;

int main() {
  ios::sync_with_stdio(false);
  cin.tie(nullptr);

  int n; cin >> n;
  string s; cin >> s;
  int j = 0, o = 0, iCnt = 0;
  for (char ch : s) {
    if (ch == 'J') j++;
    else if (ch == 'O') o++;
    else iCnt++;
  }

  cout << string(j, 'J') << string(o, 'O') << string(iCnt, 'I');

  return 0;
}