상세 컨텐츠

본문 제목

[백준] 4049 균형잡힌 세상 실버 4 - stack

알고리즘/C++

by 셉인 2023. 7. 22. 10:38

본문

728x90

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

 

4949번: 균형잡힌 세상

각 문자열은 마지막 글자를 제외하고 영문 알파벳, 공백, 소괄호("( )"), 대괄호("[ ]")로 이루어져 있으며, 온점(".")으로 끝나고, 길이는 100글자보다 작거나 같다. 입력의 종료조건으로 맨 마지막에

www.acmicpc.net

//균형잡힌 세상 실버4
//안좋은 코드
#include <iostream>
#include <string>

using namespace std;

int main (){
    string str;
    cin >> str;
    int a,b=0;
    for (int i=0; i<str.size(); i++){
        if(a==0||b==0){
            if(str[i]==']'||str[i]== ')'){
            cout <<"no";
            break;
            }
        }
        if(str[i]== '[')
        {
            a=1;
        }
        if(str[i]== ']')
        {
            a=0;
        }
        if(str[i]== '(')
        {
            b=1;
        }
        if(str[i]== ')')
        {
            b=0;
        }
        if(str.back()=='.'){//str의 마지막이 .인지 보기 위해서는 end가 아니라 back을 써야함
            if(a==0&&b==0){
                cout <<"yes";
                break;
            }
            else{
                cout <<"no";
                break;
            }
        }

    }
    return 0;
}

위에처럼 했는데 출력이 안되더라

왜 안되지 싶은.. 

단순하게 flag처럼 이용해서 (이면 1로 바꿔주고 )이면 0으로바꿔주고 0인데 )나오면 no출력해주고 마지막에 . 나왔을때 a,b둘다 0 아니면 no출력해주는 로직인데 .. 조금 수정하면 가능할 것 같기두.

//균형잡힌 세상 실버 4
//stack 이용함
#include <iostream>
#include <stack>

using namespace std;

bool isBalanced(const string& str) {
    stack<char> s;

    for (auto c : str) {
        if (c == '(' || c == '[') {
            s.push(c);
        } else if (c == ')') {
            if (s.empty() || s.top() != '(') {
                return false;
            }
            s.pop();
        } else if (c == ']') {
            if (s.empty() || s.top() != '[') {
                return false;
            }
            s.pop();
        }
    }

    return s.empty();
}

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);
    cout.tie(nullptr);

    string str;
    while (getline(cin, str)) {
        if (str == ".") {
            break;
        }

        if (isBalanced(str)) {
            cout << "yes" << endl;
        } else {
            cout << "no" << endl;
        }
    }

    return 0;
}

이거 제출해서 맞은 코드

함수를 나눠서 쓰는거 노력해야할 것 같다.

728x90

관련글 더보기

댓글 영역