알고리즘/백준
17413 : 단어 뒤집기 (C++)
가든_
2023. 7. 15. 22:50
LOGIC
- 현재 문자가 '<'라면
- stack에 문자가 있다면 answer에 추가
- 다음 문자가 '>'일때까지 answer에 문자 추가
- 입력받은 문자열만큼 반복
- stack에 문자 추가
- 현재 문자가 ' '이라면 stack에 있는 문자 answer에 추가
- stack에 있는 문자 answer에 넣고 답 출력
CODE
#include <iostream>
#include <string>
#include <stack>
using namespace std;
string input, output;
stack<char> temp;
void ReverseOutput()
{
if (!temp.empty())
{
while (true)
{
if (temp.empty()) break;
output += temp.top();
temp.pop();
}
}
}
int main()
{
getline(cin, input);
for (int i = 0; i < input.size(); i++)
{
if (input[i] == '<')
{
ReverseOutput();
while (true)
{
output += input[i];
if (input[i] == '>') break;
i++;
}
}
else
{
temp.push(input[i]);
if (input[i] == ' ')
{
temp.pop();
ReverseOutput();
output += ' ';
}
}
}
if (!temp.empty())
{
ReverseOutput();
}
cout << output;
}