알고리즘
백준 2504번 괄호의 값 C++
영춘권의달인
2022. 6. 8. 15:00
스택을 이용해서 풀었는데 풀이법을 생각하는게 좀 까다로웠다.
#include <iostream>
#include <string>
#include <vector>
#include <math.h>
#include <algorithm>
#include <utility>
#include <stack>
#include <queue>
#include <math.h>
#include <set>
#include <map>
#include <list>
#include <unordered_map>
#include <unordered_set>
#include <iomanip>
#include <limits.h>
using namespace std;
using ll = long long;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
string str;
cin >> str;
stack<char> st;
int ans = 0;
int sum = 1;
for (int i = 0; i < str.length(); i++) {
if (str[i] == '(') {
sum *= 2;
st.push(str[i]);
}
else if (str[i] == ')') {
if (st.empty() || st.top() != '(') {
ans = 0;
break;
}
if (str[i - 1] == '(') {
ans += sum;
}
sum /= 2;
st.pop();
}
else if (str[i] == '[') {
sum *= 3;
st.push(str[i]);
}
else if (str[i] == ']') {
if (st.empty() || st.top() != '[') {
ans = 0;
break;
}
if (str[i - 1] == '[') {
ans += sum;
}
sum /= 3;
st.pop();
}
}
if (!st.empty() || ans == 0) {
cout << 0;
}
else {
cout << ans;
}
};