상세 컨텐츠

본문 제목

< 백준 BaekJoon : 4949번 괄호> C++

C++/Baekjoon

by J2on 2024. 1. 22. 22:39

본문

<< 문제 >>

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';
    }
  }
}

 

 

 

관련글 더보기

댓글 영역