본문 바로가기
백준(C++)/자료구조1

[BOJ/C++]9093번_단어뒤집기

by 코잼민 2024. 7. 11.

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

#스택에 대표적인 문제..

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#include <iostream>
#include <string>
#include <stack>
 
using namespace std;
 
void init() {
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
}
 
int main() {
 
    init();
 
    int N;
 
    cin >> N;
    cin.ignore();
 
    for (int i = 0; i < N; i++) {
        stack <char> S;
        string input;
        getline(cin, input, '\n');
 
        for (int i = 0; i < input.length(); i++) {
            char c = input[i];
            if (c != ' ') {
                S.push(c);
            }
            else {
                if (!S.empty()) {
                    while (!S.empty()) {
                        char p = S.top();
                        cout << p;
                        S.pop();
                        if (S.empty()) {
                            cout << ' ';
                            break;
                        }
                    }
                }
            }
        }
 
        if (!S.empty()) {
            while (!S.empty()) {
                char p = S.top();
                cout << p;
                S.pop();
                if (S.empty()) {
                    cout << ' ';
                    break;
                }
            }
        }
        cout << '\n';
    }
 
    return 0;
}
cs