https://www.acmicpc.net/problem/4949
아이디어:
1. 입력받을 때 string tmp; getline(cin, tmp);로 한줄 입력 받고 각 글자에 auto i로 접근하여 괄호 문자인지 체크
2. tmp == "." 이면 반복문 종료
3. 닫는 괄호가 나왔을 때, 여는 괄호가 없어 pop() 할 수 없다면 그냥 스택에 넣고 마지막에 스택 비어있는지만 체크
if문 사용하는 정갈한 코드
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
string str;
while (1) {
getline(cin, str);
if (str == ".") break;
stack<char> S;
for (auto x : str) {
if (x == '(') S.push(x);
else if (x == '[') S.push(x);
else if (x == ')') {
if (!S.empty() && S.top() == '(') S.pop();
else S.push(x);
}
else if (x == ']') {
if (!S.empty() && S.top() == '[') S.pop();
else S.push(x);
}
}
if (S.empty()) cout << "yes\n";
else cout << "no\n";
}
return 0;
}
switch문 사용 코드
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
string tmp;
while (true) {
stack<char> S;
getline(cin, tmp);
if (tmp == ".") break;
for (auto i : tmp) {
switch (i) {
case '(':
S.push(i);
break;
case '[':
S.push(i);
break;
case ')':
if (S.empty()) {
S.push(i);
break;
}
else if (S.top() == '(') {
S.pop();
break;
}
else {
S.push(i);
break;
}
case ']':
if (S.empty()) {
S.push(i);
break;
}
else if (S.top() == '[') {
S.pop();
break;
}
else {
S.push(i);
break;
}
}
}
S.empty() ? cout << "yes\n" : cout << "no\n";
}
return 0;
}
'algorithm' 카테고리의 다른 글
넓이우선탐색 BFS (0) | 2025.04.05 |
---|---|
백준 3986번 좋은 단어 (0) | 2025.04.03 |
백준 11003번 최솟값 찾기 - 덱 정렬 (0) | 2025.04.01 |
백준 5430번 AC (0) | 2025.03.30 |
백준 1021번 회전하는 큐 (0) | 2025.03.30 |