본문 바로가기

백준/실버

[백준 5637번] 가장 긴 단어 (C++)

문제링크 : https://www.acmicpc.net/problem/5637

 

5637번: 가장 긴 단어

단어는 알파벳(a-z, A-Z)과 하이픈(-)으로만 이루어져 있다. 단어와 다른 문자(마침표, 숫자, 심볼, 등등등...)로 이루어진 글이 주어졌을 때, 가장 긴 단어를 구하는 프로그램을 작성하시오. Apple의

www.acmicpc.net

#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define pil pair <int, int>

int main(void) {
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    
    string check;
    string result;

    int size = 0;
    while(1)
    {
        char c = getchar();

        if (('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || c == '-')  //알파벳 또는 하이픈일때
        {
            check += c;
            if (check == "E-N-D") break;
        }
        else
        {
            if (check.size() > size)  //최대 길이 저장
            {
                size = check.size();
                result = check;
            }
            check = "";  //문자열 초기화
        }
    }

    for(int i = 0; i<size; i++)
    {
        if('A' <= result[i] && result[i] <= 'Z')
        {
            result[i] = tolower(result[i]);  //대문자를 소문자로
        }
        cout << result[i];
    }
    return 0;
}

공백과 엔터도 하나의 문자로봐야 하기 때문에 getchar로 입력을 받았다.

알파벳이나 하이픈일때 문자열에 더해주고 공백과 엔터일때 더해준 문자열의 길이를 체크한다.