[백준/C++] 2504번: 괄호의 값

-inn·2022년 1월 10일
0

백준

목록 보기
6/28

방법

코드

#include<bits/stdc++.h>
using namespace std;

string s;
int temp, ans;
stack<char> st;

int main() {
	cin >> s;
	temp = 1;
	for (int i = 0; i < s.size(); i++) {
		if (s[i] == '(') {
			temp *= 2;
			st.push(s[i]);
		}
		else if (s[i] == ')') {
			if (st.empty() || st.top() != '(') {	// 괄호 만족 X
				printf("0");
				return 0;
			}
			else if (s[i - 1] == '(') {	// ()
				ans += temp;
			}
			// (x)
			temp /= 2;
			st.pop();
		}
		else if (s[i] == '[') {
			temp *= 3;
			st.push(s[i]);
		}
		else if (s[i] == ']') {
			if (st.empty() || st.top() != '[') {	// 괄호 만족 X
				printf("0");
				return 0;
			}
			else if (s[i - 1] == '[') {	// []
				ans += temp;
			}
			//	[x]
			temp /= 3;
			st.pop();
		}
	}
	if (!st.empty())	// 문자열 다 검사 후, stack에 남았다면 에러
		ans = 0;

	printf("%d", ans);
}
profile
☁️

0개의 댓글