Algorithm/Baekjoon Online Judge

백준 17413 단어 뒤집기 2 [C++]

감성적인 개발자 2021. 8. 5. 00:54

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

 

17413번: 단어 뒤집기 2

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

www.acmicpc.net

 

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

void print(stack<char> &s){
  while (!s.empty()){
    cout << s.top();
    s.pop();
  }
}
int main(){
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);

  string str;
  stack<char> s;
  getline(cin, str);

  bool tag = false;

  for (char ch : str){

    if (ch == '<') {
      print(s); //stack에 있는거 역으로 출력
      cout << ch;
      tag = true;
    }

    else if (ch == '>') {
      tag = false;
      cout << ch;
    }

    else if (tag){
      cout << ch;
    }

    else{ // tag밖일때
      if (ch == ' '){
        print(s); //공백나오면 역순 출력
        cout << ch;
      }
      else {
        s.push(ch); //아니면 stack에 push
      }
    }
  }
  print(s);

}