4949 - 균형잡힌 세상

solution

code

#include <iostream>
#include <string>
using namespace std;

bool balance(string msg)
{
    int depth = 0;
    int start = -1, end = -1;
    bool ret = true;
    bool subbalance = true;
    string sub;

    for(int i = 0; i < msg.size(); i++)
    {
        if(msg[i] == '(')
        {
            if(start == -1)
                start = i;
            depth++;
        }
        if(msg[i] == '[')
        {
            if(start == -1)
                start = i;
            depth++;
        }
        if(msg[i] == ')')
        {
            if(msg[start] == '(' && depth == 1)
                end = i;
            depth--;
        }
        if(msg[i] == ']')
        {
            if(msg[start] == '[' && depth == 1)
                end = i;
            depth--;
        }
        if(start != -1 && end != -1)
        {
            sub = msg.substr(start+1, end-start-1);
            subbalance = balance(sub);
            start = -1, end = -1;
        }
        if(depth < 0 || !subbalance)
        {
            ret = false;
            break;
        }
    }

    if(depth != 0) ret = false;
    if(start != -1 && end == -1) ret = false;
    return ret;
}

int main()
{
    string message;
    while(1)
    {
        getline(cin, message);
        if(message == ".") break;
        if(balance(message)) cout << "yes" << endl;
        else cout << "no" << endl;
    }

    return 0;
}
#include <bits/stdc++.h>
using namespace std;

int main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  while(true){
    string a;
    getline(cin, a);
    if(a == ".") break;
    stack<char> s;
    bool isValid = true;
    for(auto c : a){
      if(c == '(' || c == '[') s.push(c);
      else if(c == ')'){
        if(s.empty() || s.top() != '('){
          isValid = false;
          break;
        }
        s.pop();
      }
      else if(c == ']'){
        if(s.empty() || s.top() != '['){
          isValid = false;
          break;
        }
        s.pop();
      }
    }
    if(!s.empty()) isValid = false;
    if(isValid) cout << "yes\n";
    else cout << "no\n";
  }
}

ref

4949번: 균형잡힌 세상