백준 algorithm
백준 - 17413 단어 뒤집기 2
cosmohoo
2020. 3. 2. 17:28
반응형

단어 뒤집기 1을 푼 방식대로 풀면 된다.
다른 점은 tag를 생각하고 풀어야한다는 점이다.
거꾸로 print하고 싶은 문자는 stack에 쌓은 후 차레대로 pop하면서 풀면 거꾸로 출력할 수 있다.
이 때 빈칸이 나오면 별개의 단어로 취급해야한다. ( tag안에 있는 단어는 해당되지 않는다. )
//
// main.cpp
// Baekjoon
//
// Created by 이준후
// Copyright © 2020 이준후. All rights reserved.
//
#include <iostream>
#include <stack>
#include <string>
using namespace std;
void WordReverse(string str)
{
int x=0;
stack<char> st;
int size = str.size()-1;
while(x<=size)
{
if(str[x]=='<')
{
while (!st.empty())
{
cout << st.top();
st.pop();
}
cout<<str[x];
x++;
while(str[x]!='>')
{
cout<<str[x];
x++;
}
cout<<str[x];
}
else if (str[x] != ' ')
st.push(str[x]);
else
{
while (!st.empty())
{
cout << st.top();
st.pop();
}
cout << ' ';
}
++x;
}
while (!st.empty())
{
cout << st.top();
st.pop();
}
cout << '\n';
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
string str;
getline(cin, str);
WordReverse(str);
return 0;
}
반응형