말랑한 하루

[BAEKJOON] 1157 단어공부 (Java) 본문

문제풀이/BAEKJOON Online Judge

[BAEKJOON] 1157 단어공부 (Java)

지수는말랑이 2022. 10. 29. 22:32
반응형

[ 학습 내용 ]
※ Comparable - compareTo

Collection(ArrayList etc)에 추가될 데이터에 정렬이 필요한 경우

class Pair_1157 implements Comparable<Pair_1157> {

  int cnt;
  char word;

  public Pair_1157(int cnt, char word) {
    this.cnt = cnt;
    this.word = word;
  }

  @Override
  public int compareTo(Pair_1157 o) {
    return o.cnt - this.cnt;
  }
}

[ 소스 코드 ]

import java.io.*;
import java.util.*;

class Pair_1157 implements Comparable<Pair_1157> {

  int cnt;
  char word;

  public Pair_1157(int cnt, char word) {
    this.cnt = cnt;
    this.word = word;
  }

  @Override
  public int compareTo(Pair_1157 o) {
    return o.cnt - this.cnt;
  }
}

public class Main {

  public static int word[] = new int[26];
  public static ArrayList<Pair_1157> ary = new ArrayList<>();

  public static void init() throws IOException {
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    char content[] = (br.readLine()).toUpperCase().toCharArray();
    for (int i = 0; i < content.length; i++) {
      word[content[i] - 'A']++;
    }
  }

  public static char solve() {
    for (int i = 0; i < 26; i++) {
      ary.add(new Pair_1157(word[i], (char) (i + 'A')));
    }
    Collections.sort(ary);
    return ary.get(0).cnt == ary.get(1).cnt ? '?' : ary.get(0).word;
  }

  public static void main(String[] args) throws IOException {
    init();
    System.out.println(solve());
  }
}



반응형
Comments