[백준 / 1159 / C++] 농구 경기

Park·2023년 9월 21일
0

코딩테스트 - Week1

목록 보기
6/15

1. 문제 접근

  • 들어오는 문자열의 맨 첫 글자의 개수를 세야하는 코드
  • 문자를 count하기 때문에 배열로 접근하자

2. 시행착오

  • 없음

3. 코드 및 풀이

3.1 배열 풀이

  • 코드에서는 count 변수를 활용해서 기권 여부를 판단했지만, 다르게 할 수 있음
#include <bits/stdc++.h>
using namespace std;

int n;
int arr[26];
int cnt = 0;
string result;

int main(){

    // 1. Input N
    cin >> n;

    // 2. Input first name and extract first char
    for(int i = 0; i < n; i++){
        string s;
        cin >> s;
        arr[s[0] - 'a']++;
    }

    // 3. count the first character above 5
    for(int i = 0; i < 26; i++){
        if(arr[i] >= 5){
            cnt++;
            result += i + 'a'; // 숫자를 문자화
        }
    }

    // 5. print result
    if (cnt == 0){
        cout << "PREDAJA";
    }
    else {
        cout << result;
    }

    return 0;
}
  • 다음과 같이 ret이라는 string변수에 해당 문자를 더해주는 방식 => ret문자의 size가 0이라면 PREDAJA 반환
#include<bits/stdc++.h>
using namespace std; 
int n, cnt[26]; 
string s, ret; 
int main(){
    cin >> n; 
    for(int i = 0; i < n; i++){
        cin >> s; 
        cnt[s[0] - 'a']++;
    }
    for(int i = 0; i < 26; i++)if(cnt[i] >= 5) ret+=  i + 'a'; 
    if(ret.size()) cout << ret << "\n"; 
    else cout << "PREDAJA" << "\n";
}

Reference

profile
안녕하세요!

0개의 댓글