1일1알

백준 17413번 단어 뒤집기 C++ 본문

알고리즘

백준 17413번 단어 뒤집기 C++

영춘권의달인 2023. 5. 15. 19:54

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

 

17413번: 단어 뒤집기 2

문자열 S가 주어졌을 때, 이 문자열에서 단어만 뒤집으려고 한다. 먼저, 문자열 S는 아래와과 같은 규칙을 지킨다. 알파벳 소문자('a'-'z'), 숫자('0'-'9'), 공백(' '), 특수 문자('<', '>')로만 이루어져

www.acmicpc.net

 

스택을 사용해서 풀었다.

'<'를 만날경우 스택에 있는것들을 비우면서 출력하고 다음 '>'가 나올때까지 나오는 문자는 바로 출력

'>'를 만날경우 다음 문자부터는 바로 출력하지 않고 스택에 삽입

' ' 를 만날경우 <>안에 있으면 넘어가고, 밖에 있으면 스택을 비운다

 

#include <iostream>
#include <string>
#include <vector>
#include <math.h>
#include <algorithm>
#include <utility>
#include <stack>
#include <queue>
#include <math.h>
#include <set>
#include <map>
#include <list>
#include <unordered_map>
#include <unordered_set>
#include <iomanip>
#include <limits.h>

using namespace std;
using int64 = long long;

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

    string str;
    getline(cin, str);

    stack<char> st;
    bool directPrint = false;
    for (int i = 0; i < str.length(); i++) {
        if (str[i] == '<') {
            directPrint = true;
            while (!st.empty()) {
                char top = st.top();
                st.pop();
                cout << top;
            }
            cout << '<';
        }
        else if (str[i] == '>') {
            directPrint = false;
            cout << '>';
        }
        else if (str[i] == ' ') {
            if (directPrint == false) {
                while (!st.empty()) {
                    char top = st.top();
                    st.pop();
                    cout << top;
                }
            }
            cout << ' ';
        }
        else {
            if (directPrint) cout << str[i];
            else st.push(str[i]);
        }
    }
    while (!st.empty()) {
        char top = st.top();
        st.pop();
        cout << top;
    }
}

'알고리즘' 카테고리의 다른 글

백준 11637번 인기 투표 C++  (1) 2023.05.19
백준 16509번 장군 C++  (0) 2023.05.16
백준 17085번 십자가 2개 놓기 C++  (1) 2023.05.14
백준 11536번 줄 세우기 C++  (0) 2023.05.13
백준 12933번 오리 C++  (0) 2023.05.12