EEALL@ONCE

๐Ÿ‘จ‍๐Ÿ’ป Map / toLowerCase/charAt/getOrDefault/Map.Entry/entrySet ๋ณธ๋ฌธ

algorithm๐Ÿ‘จ‍๐Ÿ’ป

๐Ÿ‘จ‍๐Ÿ’ป Map / toLowerCase/charAt/getOrDefault/Map.Entry/entrySet

์˜ฌ์—ฃ์›์Šค 2023. 8. 21. 22:31
728x90

๋ฌธ์ œ : 

์•ŒํŒŒ๋ฒณ ๋Œ€์†Œ๋ฌธ์ž๋กœ ๋œ ๋‹จ์–ด๊ฐ€ ์ฃผ์–ด์ง€๋ฉด, ์ด ๋‹จ์–ด์—์„œ ๊ฐ€์žฅ ๋งŽ์ด ์‚ฌ์šฉ๋œ ์•ŒํŒŒ๋ฒณ์ด ๋ฌด์—‡์ธ์ง€ ์•Œ์•„๋‚ด๋Š” ํ”„๋กœ๊ทธ๋žจ์„ ์ž‘์„ฑํ•˜์‹œ์˜ค. ๋‹จ, ๋Œ€๋ฌธ์ž์™€ ์†Œ๋ฌธ์ž๋ฅผ ๊ตฌ๋ถ„ํ•˜์ง€ ์•Š๋Š”๋‹ค.

 

๋‚˜์˜ ๋‹ต : 

import java.util.*;

public class Main {
    public static void main(String[] args) {

        Scanner s = new Scanner(System.in);

        String line= s.nextLine().toUpperCase();

        HashMap<Character,Integer> count= new HashMap<>();

        for(int i=0; i<line.length();i++){
            char c=line.charAt(i);
            count.put(c,count.getOrDefault(c,0)+1);
        }

        char mostCommon = ' ';
        int mostCount=0;
        for(Map.Entry<Character,Integer> entry : count.entrySet()){
            if(entry.getValue()>mostCount){
                mostCommon=entry.getKey();
                mostCount=entry.getValue();
            }
        }

        int check=0;
        for(Map.Entry<Character,Integer> entry : count.entrySet()) {
            if (entry.getValue() == mostCount) {
                check++;
            }
        }
        if(check>1) System.out.println("?");
        else System.out.println(mostCommon);


    }
}

 

๋ฉ”๋ชจ๋ฆฌ ์ถ•์†Œ ๋ฒ„์ „ :  HashMap -> ๋ฐฐ์—ด

 

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        String line = s.nextLine().toUpperCase();
        
        int[] count = new int[26]; // ์•ŒํŒŒ๋ฒณ ๊ฐœ์ˆ˜๋งŒํผ ๋ฐฐ์—ด ์ƒ์„ฑ
        
        for (char c : line.toCharArray()) {
            if (Character.isAlphabetic(c)) { // ์•ŒํŒŒ๋ฒณ์ธ ๊ฒฝ์šฐ์—๋งŒ ์ฒ˜๋ฆฌ
                count[c - 'A']++;
            }
        }

        int maxCount = 0;
        char mostCommon = ' ';
        boolean isUnique = true;
        
        for (int i = 0; i < 26; i++) {
            if (count[i] > maxCount) {
                maxCount = count[i];
                mostCommon = (char) (i + 'A');
                isUnique = true;
            } else if (count[i] == maxCount) {
                isUnique = false;
            }
        }
        
        if (isUnique) {
            System.out.println(mostCommon);
        } else {
            System.out.println("?");
        }
    }
}
728x90