기타등등/알고리즘 기록

[C++] 올바른 괄호

CodeJB 2021. 6. 16. 20:38

#include <iostream>
#include <stdio.h>
#include <stack>

using namespace std;
int main() {
    char str[30];
    int i , cnt =0;
    
    //카운트 하는 이유는
    //()))와 같이 )는 push를 하지 않기 때문에 empty라고 인식하기 때문에
    int opencount = 0; //열린 괄호 카운트
    int closecount = 0; //닫힌 괄호 카운트
    
    stack<char> s;
    scanf("%s",str);
    
    //가장 처음 닫힌 괄호가 들어올 것에대한 예외처리
    //예외처리 안해줘도 되긴하다. 만약 예외처리를 빼면 밑에 for문을 0부터 돌리면 된다.
    if(str[0] == '(') {
        s.push(str[0]);
        opencount++;
    }
    else { //닫힌 괄호 들어오면 그냥 끝내버린다.
        cout << "NO"<< endl;
        exit(0);
        
    }
    
    for(i = 1; str[i] != '\0'; i++){
        if(str[i] == '(')
        {
            s.push(str[i]);
            opencount++;
        }
        else if(str[i] == ')')
        {
            closecount++;
            if(!s.empty()){
                s.pop();
            }
        }
    }
    
    if(s.empty() && closecount > 0 && opencount > 0 && opencount == closecount)
        cout << "YES";
    else cout << "NO";
    
    return 0;
}

성찰

  • level2 중 쉬운 문제에 속하는 것 같다.
  • closecount를 세지 않아서 ()))에 대한 처리를 놓쳤던 것이 아쉬웠다.