해설
올바른 괄호 짝을 판별하는 문제는 스택 유형의 대표 문제이다.
문자열을 순회하면서 '('가 등장하면 이를 스택에 넣는다.
')'가 등장할 때, 스택이 비어있다면 짝이 맞는 '('가 없다는 뜻이므로 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();
}
'대딩 > 프로그래머스풀이' 카테고리의 다른 글
[프로그래머스 lv2] 최솟값 만들기 풀이 (0) | 2022.08.16 |
---|---|
[프로그래머스 lv2] 줄서는 방법 풀이 (0) | 2022.08.16 |
[프로그래머스 lv2] 땅따먹기 풀이 (0) | 2022.08.16 |
[프로그래머스 lv2] H-index 풀이 (0) | 2022.08.16 |
[프로그래머스 lv2] 가장 큰 수 풀이 (0) | 2022.08.16 |
댓글