본문 바로가기
백준

[백준] 1157번 - 단어 공부

by 템닉___ 2024. 3. 26.

문제:

시도 횟수: 3번

처음 생각한 방법: 

내 코드: 처음에 pair를 사용해서 풀어야하나 싶었는데, 굳이 쌍으로 저장할 필요없이 max플래그일때 char값을 저장하는 식으로 구현하는게 편하겠다고 생각을 했다.

// 처음 생각했던 방식이다. str의 범위 초과하는 것을 생각하지 못했다.
#include <bits/stdc++.h>
using namespace std;
int main()
{
    string str, refine;
    char c;
    int count = 1, max = 0;
    cin >> str;
    for(int i = 0; i<str.size(); i++) {
        str[i] = toupper(str[i]);
    }    
    sort(str.begin(), str.end());
    for(int i = 0; i<str.size(); i++) {
        if(str.size() == 1)
            c = str[0];
        if(str[i+1]==str[i]){
            count++;
            if(count > max) {
                max = count;
                c = str[i];
            } else if (count == max) {
                c = '?';
            }
        } else {
            count = 1;
        }
    }
    cout << c;
    return 0;
}

 

#include <bits/stdc++.h>
using namespace std;

int main()
{
    string str;
    char c;
    int count = 0, max = 0;
    cin >> str;
    
    
    for(int i = 0; i<str.size(); i++) {
        str[i] = toupper(str[i]);
    } // auto i : str이 안되었음
    
    if(str.size() == 1) {
       c = str[0];
       cout << c;
       return 0;
    }
    
    sort(str.begin(), str.end());

    for(int i = 0; i<str.size(); i++) {
        count = 1;
        while(i<str.size()-1 && str[i] == str[i+1]) {
            count++;
            i++;
        }
        if(count > max) {
            max = count;
            c = str[i];
        } else if (count == max) {
            c = '?';
        }
    }

    cout << c;
    return 0;
}

모범답안: 

// generated by chatGPT
#include <iostream>
#include <string>
#include <algorithm>

using namespace std;

int main() {
    string word;
    cin >> word;

    // 입력된 단어의 알파벳을 대문자로 변환
    transform(word.begin(), word.end(), word.begin(), ::toupper);

    int counts[26] = {0}; // 알파벳 카운트를 저장할 배열

    // 알파벳 카운트
    for(char c : word) {
        if(isalpha(c)) { // 알파벳인 경우에만 카운트
            counts[c - 'A']++;
        }
    }

    int maxCount = *max_element(counts, counts + 26); // 가장 많이 사용된 알파벳의 카운트
    int maxCountIndex = -1; // 가장 많이 사용된 알파벳의 인덱스
    int maxCountDuplicate = 0; // 가장 많이 사용된 알파벳이 여러 개인지 확인하는 변수

    // 가장 많이 사용된 알파벳의 인덱스 및 중복 여부 확인
    for(int i = 0; i < 26; ++i) {
        if(counts[i] == maxCount) {
            maxCountDuplicate++;
            maxCountIndex = i;
        }
    }

    if(maxCountDuplicate == 1) { // 가장 많이 사용된 알파벳이 하나인 경우
        cout << (char)('A' + maxCountIndex) << endl;
    } else { // 가장 많이 사용된 알파벳이 여러 개인 경우
        cout << "?" << endl;
    }

    return 0;
}

내 코드의 개선할 점: 사실 chatgpt가 쓴 코드가 좋은 건지는 잘 모르겠다. 굳이 26개의 배열 공간을 사용해야하나? 라는 생각이 들기도 한다. chatGPT에게 비교해달라고 했는데, 아뿔싸... sort를 사용해서 시간복잡도가 O(NlogN)가 되어버렸다. 맞다. 굳이 정렬할 필요는 없었는데 생각하기 편해서 정렬을 했던 것 같다. 경우의 수를 다 저장하면 굳이 정렬할 필요도 없긴 하다.
조금 더 고민해 봐야겠다.

알고리즘 분류: 구현, 문자열

난이도: 브론즈 I

복습하면서 참고해본 블로그 목록:  X

'백준' 카테고리의 다른 글

[백준] 2609번 - 최대공약수와 최소공배수  (0) 2024.03.29
[백준] 2839번 - 설탕배달  (0) 2024.03.29
[백준] 10250번 - ACM 호텔  (0) 2024.03.22
[백준] 2920번 - 음계  (1) 2024.03.22
[백준] 2522번 - 별 찍기 - 12  (0) 2024.03.22