본문 바로가기
대딩/프로그래머스풀이

[프로그래머스 lv2] 올바른 괄호 풀이

by 경아ㅏ 2022. 8. 16.

 프로그래머스의 모든 문제와 해설 보기[클릭]

 

해설

 

올바른 괄호 짝을 판별하는 문제는 스택 유형의 대표 문제이다.

 

문자열을 순회하면서 '('가 등장하면 이를 스택에 넣는다.

')'가 등장할 때, 스택이 비어있다면 짝이 맞는 '('가 없다는 뜻이므로 false를 리턴한다.

')'가 등장할 때, 스택이 비어있지 않다면 '('를 스택에서 하나 제거한다.

 

'('와 ')'를 짝 맞춰 제거한 후, 최종적으로 스택이 비어있으면 true를 리턴한다.

 

 

코드

#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <tuple>
#include <vector>
#include <stack>
#include <queue>
#include <deque>
#include <set>
#include <map>
#include <unordered_set>
#include <unordered_map>
#include <cctype>
#include <iostream>

using namespace std;
using ii = pair<int, int>;
using iii = tuple<int, int, int>;

#define X first
#define Y second

bool solution(string s) {

    stack<char> st;

    for (auto x : s) {
        if (x == '(') st.push(x);
        else if (st.empty()) return false;
        else st.pop();
    }
    return st.empty();
}

 

댓글