티스토리 뷰

https://www.acmicpc.net/problem/4949

 

4949번: 균형잡힌 세상

문제 세계는 균형이 잘 잡혀있어야 한다. 양과 음, 빛과 어둠 그리고 왼쪽 괄호와 오른쪽 괄호처럼 말이다. 정민이의 임무는 어떤 문자열이 주어졌을 때, 괄호들의 균형이 잘 맞춰져 있는지 판단

www.acmicpc.net

stack을 이용해서 풀이하였습니다.


C++ 소스 코드

#include <iostream>
#include <string>
#include <stack>
using namespace std;
int main(){
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    bool ck;
    stack<int> st;
    string str;
    while(true){
        str="";
        while(!st.empty()) st.pop();
        ck = true;
        getline(cin,str);
        if (str==".") break;
        for(int i=0;i<str.length();i++){
            if (str[i]=='('){
                st.push(1);
            }else if (str[i]=='['){
                st.push(2);
            }else  if (str[i]==')'){
                if (!st.empty() && st.top() == 1){
                    st.pop();
                }else {
                    ck =false;
                    break;
                }
            }else if (str[i]==']'){
                if (!st.empty() && st.top() == 2){
                    st.pop();
                }else {
                    ck = false;
                    break;
                }
            }
        }
        if (st.empty() && ck){
            cout << "yes" << '\n';
        }else {
            cout << "no" << '\n';
        }
    }
    return 0;
}
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/06   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
글 보관함