프로그래머스

프로그래머스 lvl 2. 올바른 괄호 [C++]

soobinida 2023. 6. 14. 13:53

올바른 괄호 ex. "()()" 또는 "(())()"

 

 

핵심 point

  • 홀수 일 경우는 올바른 괄호가 될 수 없다.
  • 짝지어졌는지 묻는 문제는 항상 'stack' 혹은 'queue'를 사용한다.

 

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

bool solution(string s)
{
    bool answer = false;
    stack<char> stk;
    if(s.length() % 2 == 0) { // 짝수 일 경우만 고려
        for(int i = 0; i < s.length(); i++) {
            if(stk.empty()) {
                stk.push(s[i]);
            } else {
            	// 스택은 Last In First Out
                if(s[i] == ')' && stk.top() == '(') {
                    stk.pop();
                } else {
                    stk.push(s[i]);
                }
            }
        }
        if(stk.empty()) answer = true;
    }
    
    return answer;
}