https://www.acmicpc.net/problem/17413
아이디어:
1. 문장의 각 문자에 대해 검사한다.
2. 문자가 '<'인 경우, ' '인 경우, 둘 다 아닐 경우로 나눈다.
3. 문자가 '<'인 경우, '>'가 나올 때 까지 그대로 출력하며 반복자를 증가시킨다.
4. 문자가 ' '인 경우, 스택을 모두 비우고 출력한 뒤 공백을 출력한다.
5. 둘 다 아닐 경우, 스택에 문자를 넣는다.
6. 반복문이 종료된 후, 스택을 비운다.
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
void emptyStack(stack<char> &s);
// Answer Code
int main()
{
stack<char> stack;
string str;
getline(cin, str);
for (int i = 0;i < str.size();i++)
{
if (str[i] == '<')
{
emptyStack(stack);
while (1)
{
cout << str[i];
if (str[i] == '>')
break;
i++;
}
}
else if (str[i] == ' ')
{
emptyStack(stack);
cout << " ";
}
else
{
stack.push(str[i]);
}
}
emptyStack(stack);
}
void emptyStack(stack<char> &s) {
while (!s.empty()) {
cout << s.top();
s.pop();
}
}
나의 풀이:
1. <tag>Inside<tag> 로 생각하고 각 태그로 감싸져있는 안쪽에 대해서 boolean형 tagInside 변수를 설정했다.
'<'와 ' '를 만나면 스택을 비우고 그대로 출력한 뒤 '<'인 경우에만 tagInside를 flase로 변경
tagInside가 true이면 스택에 push
tagInside가 false면 그대로 출력
'>'를 만나면 tagInside를 다시 true로 변경
반복문 종료 후 스택을 비워서 출력
2. 여러 조건문으로 정답에 맞게 결과를 냈지만, 풀이가 깔끔하지 않다. 그러나 참고한 풀이에서도 여러 조건문을 썼기 때문에 큰 틀은 벗어나지 않았다.
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
stack<char> str;
void emptyStack(stack<char> &s);
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
string S;
bool tagInside = true;
getline(cin, S);
for (auto i : S) {
if (tagInside && (i == ' ' || i == '<')) {
emptyStack(str);
cout << i;
if (i == '<') tagInside = false;
}
else if (tagInside) str.push(i);
else if (!tagInside) cout << i;
if (i == '>')
tagInside = true;
}
emptyStack(str);
return 0;
}
void emptyStack(stack<char> &s) {
while (!s.empty()) {
cout << s.top();
s.pop();
}
}
'algorithm' 카테고리의 다른 글
백준 2493번 탑 (0) | 2025.03.02 |
---|---|
백준 10799번 쇠막대기 (0) | 2025.02.27 |
백준 12789번 도키도키 간식드리미 (0) | 2025.02.23 |
백준 1935번 후위 표기식2, C++ 소수점 출력 (0) | 2025.02.22 |
백준 4949번 균형잡힌 세상 (0) | 2025.02.21 |