상세 컨텐츠

본문 제목

< 백준 BaekJoon : 1157번 단어공부 > C++

C++/Baekjoon

by J2on 2021. 11. 21. 19:48

본문

 << 문제 >> 

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

 

1157번: 단어 공부

알파벳 대소문자로 된 단어가 주어지면, 이 단어에서 가장 많이 사용된 알파벳이 무엇인지 알아내는 프로그램을 작성하시오. 단, 대문자와 소문자를 구분하지 않는다.

www.acmicpc.net

 

 

가장 많이 사용된 알파벳을 구하는 문제.

 

ASCII 코드를 사용하면 쉽게 해결할 수 있다.

 

알파벳 갯수 만큼의 배열을 작성하여 (ex a => 0, b=>1) 해당 알파벳이 나올때마다 배열에 +1 해준다.

 

대소문자 구분이 없기 때문에 소문자를 받았을땐 -32(A와 a의 차이)를 해주어 대문자와 동일하게 취급할 수 있다.

 

<< 코드 >>

#include <iostream>
using namespace std;

// A-Z 65-90, a-z 97-122
// char로 받고 int로 변환해서 90초과면 -32 하는게 좋을것 같다

int main() {
  int abcList[27] = {0,};
  char word[1000000] = {0,};
  
  int num;
  cin >> word;
  for (char ch:word){
    if(ch != 0){
      num = int(ch);
      if (num > 90){
        ++abcList[num-97];
      }
      else{
        ++abcList[num-65];
      }
    }
  }
  
  int index;
  int max=-1;
  bool isSame = false;

  for (int i=0; i<27; ++i) {
    if (max != 0 && abcList[i] == max){
      isSame = true;
    }
    else {
      if (abcList[i] > max) {
        max = abcList[i];
        index = i;
        isSame = false;
      }
    }
  }

  if (isSame == true){cout << "?\n";}
  else {cout << char(index + 65) << '\n';}

 

<< GitHub >>

https://github.com/J2on/BaekjoonOnlineJudge/blob/master/Code/BaekJoon_1157.cpp

 

GitHub - J2on/BaekjoonOnlineJudge: My Study

My Study. Contribute to J2on/BaekjoonOnlineJudge development by creating an account on GitHub.

github.com

관련글 더보기

댓글 영역