Baekjoon algorithm training

[백준] 1157 (단어 공부)

interfacer_han 2023. 10. 31. 11:22

#1 알고리즘

 

#2 코드

#2-1 자바

import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String testCase = sc.nextLine().trim();
        sc.close();
        
        // 대문자로 변환하고, char[]로 만듦
        char[] upperCaseChars = testCase.toUpperCase().toCharArray();
        
        // 대문자 알파벳의 갯수를 담을 Map
        Map<Character, Integer> charCountMap = new HashMap<Character, Integer>();
        
        // 알파벳의 종류와 그 갯수 저장
        for(char element : upperCaseChars) {
            if(charCountMap.containsKey(element)) {
                charCountMap.put(element, charCountMap.get(element) + 1);

            } else {
                charCountMap.put(element, 1);
            }
        }
        
        int maxNumber = -1;
        char maxNumberAlphabet = ' '; // 공백 문자
        
        // Map은 내부 인터페이스인 Map.Entry 인터페이스를 사용하여 키-값 쌍을 저장한다
        for(Map.Entry<Character, Integer> entry : charCountMap.entrySet()) {
            if(entry.getValue() > maxNumber) {
                maxNumber = entry.getValue();
                maxNumberAlphabet = entry.getKey();
            
            } else if(entry.getValue() < maxNumber) {
                continue;
                
            } else { // entry.getValue() == maxNumber
            	maxNumberAlphabet = '?';

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

 

#2-2 코틀린

fun main() {
    val testCase = readln().trim()

    /*
     * 대문자로 변환 -> CharArray로 변환 -> Array<Char>로 변환
     * Array<Char>가 더 보기 좋아서 CharArray 대신 사용했다
     */
    val upperCaseChars : Array<Char> = testCase.uppercase().toCharArray().toTypedArray()

    /*
     * 대문자 알파벳의 갯수를 담을 Map 선언
     * 맵 '내부'의 데이터가 변하는 것이기에 val로 선언해도 된다.
     * val은 charCountMap이라는 참조 변수(Reference Types)가,
     * 초기화 시 할당되었던 객체를 앞으로 바꾸지 않겠다는 의미다.
     */
    val charCountMap = HashMap<Char, Int>()

    // 알파벳의 종류와 그 갯수 저장
    for(element : Char in upperCaseChars) {
        if(charCountMap.containsKey(element)) {
            charCountMap[element] = charCountMap[element]!! + 1

        } else {
            charCountMap[element] = 1
        }
    }

    var maxNumber = -1;
    var maxNumberAlphabet = ' '; // 공백 문자

    // Map 내부 인터페이스인 Map.Entry 인터페이스를 사용하여 키-값 쌍을 저장한다
    for((key, value) in charCountMap) {
        if(value > maxNumber) {
            maxNumber = value
            maxNumberAlphabet = key

        } else if(value < maxNumber) {
            continue;

        } else { // value == maxNumber
            maxNumberAlphabet = '?';

        }
    }

    println(maxNumberAlphabet)
}