알고리즘/BOJ
[c/c++] BOJ 2504번 문제 - 괄호 값
wonjun.Aden
2022. 3. 11. 00:08
https://www.acmicpc.net/problem/2504
2504번: 괄호의 값
4개의 기호 ‘(’, ‘)’, ‘[’, ‘]’를 이용해서 만들어지는 괄호열 중에서 올바른 괄호열이란 다음과 같이 정의된다. 한 쌍의 괄호로만 이루어진 ‘()’와 ‘[]’는 올바른 괄호열이다. 만일
www.acmicpc.net
문제

문제풀이
#include <bits/stdc++.h>
using namespace std;
//괄호의 값
int main(){
ios::sync_with_stdio(0);
cin.tie(0);
string s;
cin >> s;
stack<char> st;
int ans=0;
int num =1;
for(int i=0;i<s.size();i++){
if(s[i] == '('){
num *= 2;
st.push(s[i]);
}else if(s[i]=='['){
num *= 3;
st.push(s[i]);
}else if(s[i] == ')'){
//예외의 경우? empty이거나 [ 일 경우?
if(st.empty() || st.top()!='('){
cout << 0;
//바로 종료
return 0;
}
//num의 값을 더하고 num는 다시 초기화
if(s[i-1] == '(') ans += num;
st.pop();
num /=2;
}else{
//']'
if(st.empty() || st.top()!='['){
cout << 0;
return 0;
}
if(s[i-1] == '[') ans += num;
st.pop();
num /=3;
}
}
if(st.empty()) cout << ans;
else cout << 0;
return 0;
}
문제의 포인트
- 2와 3을 곱해주고 더하고 다시 나눠줘야함!
반응형