BOJ 1157 단어 공부

1 개요[ | ]

BOJ 1157 단어 공부
  • 주어진 단어 중 가장 많이 사용된 알파벳을 출력하는 문제
  • 알고리즘 분류: 문자열 처리

2 C++[ | ]

#include <iostream>
#include <string>
#include <algorithm>
using namespace std;

int main() {
    string str;
    cin >> str;
    transform(str.begin(), str.end(), str.begin(), ::toupper);
    int counts[26] = {0};
    int len = str.length();
    for(int i=0; i<26; i++) {
        char c = 65+i;
        for(int j=0; j<len; j++) {
            if(str[j] == c) counts[i]++;
        }
    }
    int max_count = 0;
    for(int i=0; i<26; i++) {
        if( counts[i] > max_count ) max_count = counts[i];
    }
    char max_char; 
    int max_count_count = 0;
    for(int i=0; i<26; i++) {
        if( counts[i] == max_count ) {
            max_char = 65+i;
            max_count_count++;
        }
    }
    if( max_count_count > 1 ) {
        cout << "?\n";
    } else {
        cout << max_char << '\n';   
    }
}

3 Java[ | ]

import java.util.*;
public class Main {
    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);
        String word = sc.next().toUpperCase();
        int[] counts = new int[26];
        for(int i=0; i<word.length(); i++) {
            int k = word.charAt(i) - 'A';
            counts[k]++;
        }
        //System.out.println( Arrays.toString(counts) );
        
        int max = -1;
        int max_key = -1;
        for(int i=0; i<26; i++) {
            if( counts[i] > max ) {
                max = counts[i];
                max_key = i;
            }
        }
        int max_count = 0;
        for(int i=0; i<26; i++) {
            if( counts[i] == max ) {
                max_count++;
            }
        }
        if( max_count > 1 ) {
            System.out.println("?");
        }
        else {
            System.out.println((char)('A' + max_key));
        }
    }
}

4 PHP[ | ]

<?php
$str = strtoupper(rtrim(fgets(STDIN)));
$count_chars = count_chars($str);
arsort($count_chars);
$values = array_values($count_chars);
if( $values[0] == $values[1] ) {
    echo '?';
    exit;
}
$keys = array_keys($count_chars);
echo chr($keys[0]);

5 Python[ | ]

s = input().upper()
cnts = [0] * 27
for i in range(0, 26):
    cnts[i] = s.count(chr(i+65))
max = max(cnts) 
if cnts.count(max) >= 2: 
    print('?')
else:
    print(chr(cnts.index(max)+65))
문서 댓글 ({{ doc_comments.length }})
{{ comment.name }} {{ comment.created | snstime }}