coding_test/BAEKJOON

백준 5637번 C++ 풀이

CodeJin 2022. 1. 2. 16:05

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

 

5637번: 가장 긴 단어

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

www.acmicpc.net

 

 

입력받은 단어들 중에 제일 긴 단어를 출력하는 문제. 이때 단어는 알파벳과 하이픈만으로 구분하기 때문에 이에 유의해야한다.

 

공백을 기준으로 입력받고, 알파벳과 하이픈을 제거한 후에, 길이를 비교하여 풀었다.

 

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

string preprocess(string str) {
    string result = "";

    for (auto iter = str.begin(); iter != str.end(); iter++) {
        if (isalpha(*iter) || *iter == '-') {
            result += *iter;
        }
    }
    return result;
}

int main () {
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);
    
    string max = "";
    string str;
    
    while (true) {
        cin >> str;
        if (str == "E-N-D") break;
        str = preprocess(str);
        max = max.length() < str.length() ? str : max;
    }

    for (auto iter = max.begin(); iter != max.end(); iter++) 
       *iter = tolower(*iter);
    
    cout << max;
}