<< 문제 >>
https://www.acmicpc.net/problem/4949
4949번: 균형잡힌 세상
각 문자열은 마지막 글자를 제외하고 영문 알파벳, 공백, 소괄호("( )"), 대괄호("[ ]")로 이루어져 있으며, 온점(".")으로 끝나고, 길이는 100글자보다 작거나 같다. 입력의 종료조건으로 맨 마지막에
www.acmicpc.net
괄호에 짝을 이루어야 하는 문제
) 가 나왔을 때 stack의 top이 ( 이어야 하고
] 가 나왔을 때 top이 [ 이어야 한다.
이 두가지만 생각하면 어렵지 않다.
<< 코드 >>
#include <iostream>
#include <stack>
#include <string>
using namespace std;
bool checkString(const string &str) {
stack<char> st;
int round = 0;
int square = 0;
for (char ch : str) {
if (ch == '(') {
round++;
st.push(ch);
}
else if (ch == '[') {
square++;
st.push(ch);
}
else if (ch == ')') {
if (!st.empty() && st.top() == '(') {
round--;
st.pop();
}
else{
return false;
}
}
else if (ch == ']') {
if (!st.empty() && st.top() == '[') {
square--;
st.pop();
}
else{
return false;
}
}
}
if (round == 0 && square == 0) {
return true;
} else {
return false;
}
}
int main() {
string input;
while(1){
getline(cin, input);
if(input == "."){ break; }
if (checkString(input)) {
cout << "yes" << '\n';
} else {
cout << "no" << '\n';
}
}
}
< 백준 BaekJoon : 18258번 큐 2> C++ (0) | 2024.01.23 |
---|---|
< 백준 BaekJoon : 12789번 도키도키 간식드리미> C++ (0) | 2024.01.23 |
< 백준 BaekJoon : 9012번 괄호> C++ (0) | 2024.01.22 |
< 백준 BaekJoon : 10773번 제로> C++ (0) | 2024.01.22 |
< 백준 BaekJoon : 28278번 스택 2> C++ (0) | 2024.01.22 |
댓글 영역