Baekjoon Algorithm | Problem 1157: Word Study

Source

https://www.acmicpc.net/problem/1157

Problem

Solve Baekjoon Online Judge problem 1157, Word Study.

Input

Follow the input format and constraints given in the original problem statement.

Output

Print the answer required by the problem.

Sample Input 1

Mississipi

Sample Output 1

?

Sample Input 2

zZa

Sample Output 2

Z

Sample Input 3

baaa

Sample Output 3

A

Algorithm Classification

  • Math
  • Implementation

Solution

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;

public class Main {

    public static void main(String[] args) throws IOException {
        try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) {
            String input = br.readLine();

            Map<Character, Integer> alphabetCountMap = new HashMap<>();

            Set<Character> maxSet = new HashSet<>();
            int max = Integer.MIN_VALUE;

            for (int i = 0; i < input.length(); i++) {
                Character alphabet = Character.toUpperCase(input.charAt(i));

                int count;
                if (alphabetCountMap.containsKey(alphabet)) {
                    count = alphabetCountMap.get(alphabet) + 1;
                } else {
                    count = 0;
                }
                alphabetCountMap.put(alphabet, count);

                if (max < count) {
                    max = count;
                    maxSet.clear();
                    maxSet.add(alphabet);
                } else if (max == count) {
                    maxSet.add(alphabet);
                }
            }

            if (maxSet.size() > 1) {
                System.out.println("?");
            } else {
                System.out.println(maxSet.iterator().next());
            }
        }
    }
}
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main2 {

    public static void main(String[] args) throws IOException {
        try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) {
            String input = br.readLine();

            int[] alphabet = new int[26];
            for (int i = 0; i < input.length(); i++) {
                //char c = Character.toUpperCase(input.charAt(i));
                //alphabet[c - 65]++;
                char c = input.charAt(i);
                if (c >= 'a')
                    alphabet[c - 'a']++;
                else
                    alphabet[c - 'A']++;
            }

            char output = 0;
            int max = Integer.MIN_VALUE;
            for (int i = 0; i < alphabet.length; i++) {

                if(max < alphabet[i]) {
                    max = alphabet[i];
                    output = (char) (i + 'A');
                } else if(max == alphabet[i]) {
                    output = '?';
                }
            }

            System.out.println(output);
        }
    }
}