본문 바로가기
Problem Solving

[Problem Solving] BOJ 17413 : 단어 뒤집기 2

by __K.Jun__ 2025. 1. 11.

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

 

<>안에 있는 것은 <>포함해서 그대로 출력하고, 아닌 것은 공백 단위로 끊어서 거꾸로 뒤집어서 출력한다.

 

1. 공백이 아닌 문자를 만난 경우

스택에 문자를 추가한다.

2. 공백 또는 i가 마지막 인덱스인 경우

스택에 있는 것을 모두 출력하고 공백 출력

3. <를 만난 경우

스택 top을 순서대로 모두 출력하고, <>를 그대로 출력

 

#include <iostream>
#include <vector>
#include <queue>
#include <cstring>
#include <map>
#include <algorithm>
#include <stack>
#include <set>
#include <cmath>
#include <climits>
#define endl '\n'
using namespace std;

string S;

void input()
{
    getline(cin, S);
}

void solution()
{
    stack<char> st;
    int sz = S.size();
    for (int i = 0; i < sz; i++)
    {
        if (S[i] == '<')
        {
            while (!st.empty())
            {
                cout << st.top();
                st.pop();
            }
            while (S[i] != '>')
            {
                cout << S[i];
                i++;
            }
            cout << ">";
            continue;
        }
        if (S[i] != ' ')
        {
            st.push(S[i]);
        }
        if (S[i] == ' ' || i == sz - 1)
        {
            while (!st.empty())
            {
                cout << st.top();
                st.pop();
            }
            cout << " ";
        }
    }
}

void output()
{
}

int main(void)
{
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);
    cout.tie(nullptr);

    input();
    solution();
    // output();

    return 0;
}
728x90