알고리즘
백준 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;
}
}