작성일 :

문제 링크

9046번 - 복호화

설명

주어진 문장에서 가장 빈번하게 나타나는 알파벳을 출력하는 문제입니다.


접근법

공백을 제외하고 알파벳 빈도를 셉니다.

최댓값이 여러 개면 ?, 하나면 해당 문자를 출력합니다.


Code

C#

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
using System;

class Program {
  static void Main() {
    var t = int.Parse(Console.ReadLine()!);
    for (var tc = 0; tc < t; tc++) {
      var line = Console.ReadLine()!;
      var cnt = new int[26];
      foreach (var ch in line) {
        if (ch == ' ') continue;
        cnt[ch - 'a']++;
      }

      var best = 0;
      for (var i = 0; i < 26; i++)
        if (cnt[i] > best) best = cnt[i];

      var idx = -1;
      var many = 0;
      for (var i = 0; i < 26; i++) {
        if (cnt[i] == best) { idx = i; many++; }
      }

      if (many > 1) Console.WriteLine("?");
      else Console.WriteLine((char)('a' + idx));
    }
  }
}

C++

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <bits/stdc++.h>
using namespace std;

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

  int t; cin >> t;
  string line;
  getline(cin, line);

  for (int tc = 0; tc < t; tc++) {
    getline(cin, line);
    int cnt[26] = {};
    for (char ch : line) {
      if (ch == ' ') continue;
      cnt[ch - 'a']++;
    }

    int best = 0;
    for (int i = 0; i < 26; i++)
      if (cnt[i] > best) best = cnt[i];

    int idx = -1, many = 0;
    for (int i = 0; i < 26; i++) {
      if (cnt[i] == best) { idx = i; many++; }
    }

    if (many > 1) cout << "?\n";
    else cout << char('a' + idx) << "\n";
  }

  return 0;
}