문제 설명

문자열 s가 주어집니다.

이 문자열에서 가장 많이 등장하는 문자를 출력하는 프로그램을 구현하세요.

단, 가장 많이 등장하는 문자열이 여러 개라면 사전순으로 정렬했을 때 더 앞에 위치하는 문자를 출력합니다.


입력 형식

· s : 알파벳 소문자로 이루어진 문자열


출력 형식

· 문자열에서 가장 많이 등장하는 문자를 문자열로 출력


제약 사항

· 0 < s.length <= 100


입출력 예시

·  입력

      · s= "google"

· 출력 : "g"

· 설명 : g와 o가 똑같이 2번씩 등장하나, 사전순 정렬에서 g가 먼저 오므로 답은 g이다.


작성 코드

class Solution {
    public String solution(String s) {
        int[] count = new int[26]; // 소문자 26개
        
        // 문자열 s의 각 문자를 검사하면서 소문자의 경우에만 count 배열의
        // 해당 인덱스 값을 1 증가 시킨다.
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (c >= 'a' && c <= 'z') {
                count[c - 'a']++;
            }
        }

        char mostFrequentChar = '\0'; // null 문자로 초기화
        int maxCount = 0;
        for (int i = 0; i < 26; i++) {
            if (count[i] > maxCount) {
                mostFrequentChar = (char) ('a' + i); // a의 아스키 코드 값은 97
                // i가 0일때 a, 1일때 97 + 1 -> 즉 b가 됨
                maxCount = count[i]; // count 배열에서 가장 많이 발생한 문자를 찾음
            }
        }
        for (int i = 0; i < 26; i++) {
            if (count[i] == maxCount && (char) ('a' + i) < mostFrequentChar) {
                mostFrequentChar = (char) ('a' + i);
            }
        }
        // 가장 많이 발생한 문자를 String으로 반환
        return String.valueOf(mostFrequentChar);
    }

    public static void main(String[] args) {
        Solution st = new Solution();
        String s = "google";
        System.out.println(st.solution(s));
    }
}

 

정답 코드

import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

class Solution {
    public String solution(String s) {
        Map<Character, Integer> map = new HashMap<>();

        for (char c: s.toCharArray()) {
            if (!map.containsKey(c)) {
                map.put(c, 0);
            }
            map.put(c, map.get(c) + 1);
        }

        Character mostAppearChar = null;
        int appearCount = 0;

        List<Character> chars = map.keySet()
                .stream()
                .collect(Collectors.toList());
        chars.sort(Comparator.naturalOrder());

        for (char c: chars) {
            int count = map.get(c);
            if (appearCount < count) {
                mostAppearChar = c;
                appearCount = count;
            }
        }
        return String.valueOf(mostAppearChar);
    }
    
    public static void main(String[] args) {
        Solution st = new Solution();
        String s = "google";
        System.out.println(st.solution(s));
    }
}